2

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.

ChrisM
  • 1,576
  • 6
  • 18
  • 29
Chiien
  • 341
  • 1
  • 3
  • 14

1 Answers1

4

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

AT82
  • 71,416
  • 24
  • 140
  • 167
  • thanks a lot!! it's working!! yes, I mixed reactive forms with template driven. I am still learning!! One more thing, how can I directly set the values in the reactive form?? thanks again!! – Chiien Dec 20 '17 at 18:47
  • What do you mean *directly setting values in reactive form*? If you mean like setting values to your array, it's what I have done, otherwise you can also set values to any form controls: https://stackblitz.com/edit/angular-1mavrl?file=app/app.component.ts – AT82 Dec 20 '17 at 18:59
  • if interested in trying to use ngFor in template-driven forms check here: https://stackoverflow.com/questions/39615780/angular-2-template-driven-form-with-ngfor-inputs?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – sarora May 22 '18 at 20:02