Strange formArray behavior in Angular2

365 views Asked by At

I found what I think may be a bug, but not sure.

If I use this code:

<div formArrayName="techs" >
  <div *ngFor="let tech of techListInFB | async; let i=index">                  
    <md-checkbox [formControlName]="i">
      {{tech.$key}} - {{tech.name}}
    </md-checkbox>
  </div>
</div>

I get this error and my app crashes:

Cannot find control with path: 'techs -> 0'

But if I add this one line anywhere in the component's template:

  {{techListInFB | async}}

Everything works fine. So how could this one line possibly remove the error? I don't see what the line is doing to change anything.

1

There are 1 answers

0
Pezetter On

I do not have much experience with Nested Model-driven Forms, but I found a couple of resources.

Heres the meat and potatoes of a through example:

    <div formArrayName="addresses">
      <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">
        <div class="panel-heading">
          <span>Address {{i + 1}}</span>
          <span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)"></span>
        </div>
        <div class="panel-body" [formGroupName]="i">
          <div class="form-group col-xs-6">
            <label>street</label>
            <input type="text" class="form-control" formControlName="street">
            <small [hidden]="myForm.controls.addresses.controls[i].controls.street.valid" class="text-danger">
                Street is required
            </small>
          </div>
          <div class="form-group col-xs-6">
            <label>postcode</label>
            <input type="text" class="form-control" formControlName="postcode">
          </div>
        </div>
      </div>
    </div>

and the controller:

  public myForm: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.myForm = this._fb.group({
            name: ['', [Validators.required, Validators.minLength(5)]],
            addresses: this._fb.array([
                this.initAddress(),
            ])
        });
    }

    initAddress() {
        return this._fb.group({
            street: ['', Validators.required],
            postcode: ['']
        });
    }

    addAddress() {
        const control = <FormArray>this.myForm.controls['addresses'];
        control.push(this.initAddress());
    }

    removeAddress(i: number) {
        const control = <FormArray>this.myForm.controls['addresses'];
        control.removeAt(i);
    }

plnkr with working relatively complex forms, which comes from here.

I'd like to see your component/controller too