【问题标题】:Accessing FormArray inside nested FormGroup , angular6访问嵌套 FormGroup 内的 FormArray , angular6
【发布时间】:2019-08-03 22:43:42
【问题描述】:

我有一个简单的反应形式

  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>

ERROR TypeError: Cannot read property 'controls' of undefined

请帮忙

【问题讨论】:

  • 不会是let itemrow of secondFormGroup.connectionRow 吗?
  • 甚至outerForm.get('secondFormGroup').get('connectionRow').controls。你可以把它放在一个 gette 中,然后在你的模板中使用它

标签: angular angular-reactive-forms formarray


【解决方案1】:

您错过了在模板中提及 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>

【讨论】:

  • 是的,可以,你能告诉我如何在输入下添加错误字段吗?
  • @raju 如果对您有帮助,请将答案标记为正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多