首页 > 解决方案 > 让子组件知道它是父组件 Angular 的 FormGroup 的一部分

问题描述

我有一个FormGroup将它的一些字段引用到另一个使其成为子组件的组件。但是,每当我在rendering孩子的舞台上时,我都会收到此错误

Error: formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup...

当您formControlNameFormGroup. 我已确保父级在其子级之前首先呈现 FormGroup,并且正确地,这是默认行为。

父 HTML 是这样的。

<form [formGroup]="form.formGroup" #formDirective="ngForm" (ngSubmit)="saveForm(formDirective)">
      <input matInput formControlName="form.mainInputControl" placeholder="This one doesn't have a problem" type="text">
      <child-component [details]="form.detailsForChild"></child-component>
</form>

子 HTML 是这样的

<mat-checkbox formControlName="detailsForChild.checkBoxControl"></mat-checkbox>

PS:这不是真正的变量名,我只是这样做,所以它会很直观。

标签: angularformscomponentsangular-reactive-forms

解决方案


显然,子组件和父组件不能像我想的那样在运行时混淆。

所以我需要将确切的信息传递FormGroup给孩子并将其绑定到formControlName谎言所在的更高一级的元素。

所以从例子中。

Parent

<form [formGroup]="form.formGroup" #formDirective="ngForm" (ngSubmit)="saveForm(formDirective)">
      <input matInput formControlName="form.mainInputControl" placeholder="This one doesn't have a problem" type="text">
      <child-component [details]="form.detailsForChild" [parentForm]="form.formGroup"></child-component>
</form>

孩子

<ng-container [formGroup]="parentForm">
    <mat-checkbox formControlName="detailsForChild.checkBoxControl"></mat-checkbox>
</ng-container>

参考:这里


推荐阅读