在嵌套的 FormGroup 中访问 FormArray,angular6

Accessing FormArray inside nested FormGroup , angular6

我有一个简单的反应形式

  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: ['']
        }])
      })
    });
  }

我可以在 UI 中显示它。但是我无法显示 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>

错误类型错误:无法读取未定义的 属性'controls'

请帮忙

您没有在模板中提及 formArrayName。

更新在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>

而在TS文件中

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

要处理每个输入的错误,请将它们包装在一个 mat-form-field 容器中。您可以参考以下内容

<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>