简体   繁体   中英

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM