Search code examples
angularngforangular4-formsngmodelformarray

angular 4 material show formArrayName with ngFor and ngModel


I am trying to show an array of emails with Angular 4 react form and bind an array from my inputs, so in the component I wrote this:

<li>
 <h4>Telephone</h4>
 <div class="lists" formArrayName="telephones">
  <mat-form-field *ngFor="let telephone of userData.telephones; let i = index">
   <input matInput [(ngModel)]="telephone">
  </mat-form-field>
 </div>
</li>

I need to show a telephone number array and I want to make its fields editable with ngModel.

I've tried a lot things: a formArrayName solution with [formGroupName]="index" and formControlName="", but it didn't work. Also a ngModel with ngFor solution that requires a unique name.


Solution

  • Don't mix reactive forms with template driven. Choose either. Since you are working with an array, use a reactive forms. Seems your array is of primitive type, which means that you can assign the values directly without looping the array.

    constructor(private fb: FormBuilder) {
      this.myForm = this.fb.group({
        telephones: this.fb.array(this.userData.telephones)
      });
      // if receiving data at a later point, use below instead
      //this.myForm.setControl('telephones', this.fb.array(this.userData.telephones))
    }
    

    And then in your template just iterate your form array (here without angular material):

    <div formArrayName="telephones">
      <div *ngFor="let tel of myForm.controls.telephones.controls; let i = index">
        <input [formControlName]="i" />
      </div>
    </div>
    

    StackBlitz