How to get access to formControl element in formBuilder Array?

Viewed 35

I'm trying to get value from mat-autocomplete but if I'm using formControlName mat-autocomplete doesn't work.

<mat-form-field>
     <mat-label>...</mat-label>
          <input type="text" matInput aria-label="..."
                     //[formControl]="attributeListCtrl"
                       formControlName="attributeKey"
                       [matAutocomplete]="auto" [readonly]="VOForm.get('VORows').value[i].isEditable">
           <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="onDBAttrSelected()">
           <mat-option *ngFor="let option of attributeList" [value]="option">
               {{option.nameAttribute}}
           </mat-option>
      </mat-autocomplete>
</mat-form-field>

I have seen that some people recommend to use something like [formControl]= form.get('attributeKey') but it's not working for me because there's nested array with groups in my formBuilder

this.VOForm = this.fb.group({
        VORows: this.fb.array(this.attributeList.map((val:any) => this.fb.group({
            idx: new FormControl('1'),
            attributeKey: new FormControl<string | Attribute>(''),
            attributeValue: new FormControl(val.attribute.allValue),
            action: new FormControl('existingRecord'),
            isEditable: new FormControl(true),
            isNewRow: new FormControl(false),
          })

      )) //end of fb array
      }); 
1 Answers

A FormArray of formGroups is always the same:

You use a getter in .ts

get VORows()
{
   return this.VOForm.get('VORows') as FormArray
}

In .html

<!--declare the form-->
<form [formGroup]="VOForm">

  <!--use formArrayName-->
  <div formArrayName="VORows">

   <!--iterate over the formArray.controls using the "getter"-->
   <div *ngFor="let group of VORows.controls;let i=index"
        [formGroupName]="i">

        <!--here you add the "inputs" using formControlName-->
        <mat-form-field>
          <mat-label>...</mat-label>
          <input type="text" matInput aria-label="..."

                       formControlName="attributeKey"
                       [matAutocomplete]="auto" 
                       ...

             <!--if we want to get reference of another formControl we can use
                 dot notation
             -->                       
            [readonly]="VOForm.get('VORows.'+i+'.isEditable').value">

            <mat-autocomplete #auto="matAutocomplete" 
               [displayWith]="displayFn" ...>

               <mat-option *ngFor="let option of attributeList" [value]="option">
                 {{option.nameAttribute}}
             </mat-option>
           </mat-autocomplete>
</mat-form-field>
Related