簡體   English   中英

讓子組件知道它是父組件 Angular 的 FormGroup 的一部分

[英]Let know Child Component that it is part of FormGroup of Parent Component Angular

我有一個FormGroup將它的一些字段引用到另一個使其成為子組件的組件。 但是,每當我處於孩子的rendering階段時,我都會收到此錯誤

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

當您在FormGroup之外的字段上包含formControlName屬性時,這是一個一般性錯誤。 我已確保父級在其子級之前首先呈現 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:這不是真正的變量名,我只是這樣做,所以它會很直觀。

顯然,子組件和父組件不能像我想的那樣在運行時混淆。

因此,我需要將確切的FormGroup傳遞給 Child 並將其綁定到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>

參考: 這里

您需要添加 formControlName

 <child-component formControlName="form.detailsForChild"></child-component>
您需要在子組件中編寫以下代碼

 import {ControlContainer, FormControl} from '@angular/forms'; @Component({ // Ensure we either have a [formControl] or [formControlName] with our child-component selector: '[formControl] child-component,[formControlName] child-component', templateUrl: './address-editor.component.html' }) export class ChildComponent implements OnInit { public checkBoxControl: FormControl; // Let Angular inject the control container constructor(private controlContainer: ControlContainer) { } ngOnInit() { // Set our addressFormGroup property to the parent control // (ie FormGroup) that was passed to us, so that our // view can data bind to it this.checkBoxControl = this.controlContainer.control; } }
 //Child component code <mat-checkbox formControlName="checkBoxControl"></mat-checkbox>

更多信息請點擊鏈接

在子組件中添加 formGroup

家長

<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 [parentFormGroup]="form.formGroup" [details]="form.detailsForChild"></child-component>
</form>

孩子

<div [formGroup]="parentFormGroup">
    <mat-checkbox formControlName="detailsForChild.checkBoxControl"></mat-checkbox>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM