Home > OS >  Get formcontrolname of FormGroup in an FormArray
Get formcontrolname of FormGroup in an FormArray

Time:02-10

I have a FormGroup with a FormArray that has 3 FormControls. I want to iterate trough the FormArray and display the values of each one in a form. But I'm stuck on what to put on the FormControlName.

This is my FormGroup:

fg: FormGroup = new FormGroup({
    properties: new FormArray([])
  }); 

This is how I add the FormControls into my FormArray,dataArray is the data I get from my response:

let formArray = this.fg.get('properties') as FormArray;
    for(let property of dataArray){
      const userPropertyGroup = new FormGroup({
        user_id: new FormControl("", Validators.required),
        name: new FormControl("", Validators.required),
        value: new FormControl("", Validators.required),
      });

      formArray.push(userPropertyGroup); 

To set the values in the FormArray:

 for(let i = 0; i < dataArray.length; i   ){
      formArray.controls[i].setValue({
          user_id: dataArray[i].user_id,
          name: dataArray[i].name,
          value: dataArray[i].value,
        })
    }

Now I want to iterate and display all the values in the form. With {{property.value.name}} I'm able to get the values of each property of the array but I'm stuck at the formControlName. What should go there?

 <form [formGroup]="fg" >
    <table *ngFor="let property of fg.get('properties')['controls']" >
        {{property.value.name}}
      <tr>
        <td>
          <mat-form-field >
            <input matInput formControlName="?????" placeholder="User id">
          </mat-form-field>
        </td>

I checked a lot of similar questions at StackOverflow but none of them helps. I also tried implementing this example from Angular docs. Any help is really appreciated! Thanks.

CodePudding user response:

You would need to structure your html as below:

<form [formGroup]="fg">
  <ng-container formArrayName="properties">
    <div *ngFor="let property of properties.controls; let i = index"> <!-- Iterate over FormArray controls -->
      <ng-container [formGroupName]="i"> <!-- Since each control within FormArray is a FormGroup -->
          <input formControlName="user_id" type="text" />
          <input formControlName="name" type="text" />
          <input formControlName="value" type="text" />
      </ng-container>
    </div>
  </ng-container>
</form>

Define a getter within your ts component file to get the properties FormArray:

get properties(): FormArray {
  return this.fg.get('properties') as FormArray;
}

PS: I haven't specified any CSS classes or Angular Material components in HTML, to keep the structure simple, so that it's easy to understand the hierarchy. Also I have used ng-container, you can use elements as per your use case.

  • Related