Search code examples
angularangular-reactive-formsformarray

Accessing FormArray inside nested FormGroup , angular6


I have a simple reactive form

  ngOnInit() {
    this.outerForm = this._formBuilder.group({
      firstFormGroup: this._formBuilder.group({
        nserNumber: ['', [Validators.required, Validators.pattern(this.spacePattern)]],            
      }),
      secondFormGroup: this._formBuilder.group({
        nser1Number: ['', [Validators.required, Validators.pattern(this.spacePattern)]],
        connectionRow: this._formBuilder.array([{
          connectionType: [''],
          switchHostname: ['']
        }])
      })
    });
  }

I am able to display this in UI. But I am unable to display connectionRow

<fieldset formGroupName="secondFormGroup">
      <input matInput placeholder="PID number" id='nser1Number' formControlName="nser1Number">

    <div class='formRow' *ngFor="let itemrow of connectionRow.controls; let i=index" [formGroupName]="i">
        {{i}}
    </div>
  </fieldset>

ERROR TypeError: Cannot read property 'controls' of undefined

Please help


Solution

  • You missed to mention formArrayName in the template.

    Update in the HTML

    <fieldset formGroupName="secondFormGroup">
        <input matInput placeholder="PID number" id='nser1Number' formControlName="nser1Number">
        <div formArrayName="connectionRow">
            <div class='formRow' *ngFor="let itemrow of connectionRow.controls; let i=index" [formGroupName]="i">
                <input matInput placeholder="Tenant" formControlName="connectionType">
                <input matInput placeholder="Tenant" formControlName="switchHostname">
            </div>
        </div>
    </fieldset>
    

    And in the TS file

    get connectionRow(): FormArray {
        return this.outerForm.get('secondFormGroup').get("connectionRow") as FormArray;
    }
    enter code here
    

    To handle errors for each input wrap them inside a mat-form-field container. You may refer the below

    <mat-form-field>
        <input matInput placeholder="Enter your email" formControlName="connectionType" required>
        <mat-error *ngIf="connectionRow.controls[i].connectionType.invalid">Your message</mat-error>
    </mat-form-field>