简体   繁体   中英

Angular 4 FormGroup - Pass parent form controls to child component

I am using Angular Reactive Forms FormGroup and FormArray. I am trying to split out my form fields into child components but am having trouble passing the parent form controls to the child which I feel should simple. My parent FormGroup is title 'binsForm' and I am referencing the child component in my template like:

<app-child [parent]="binsForm"></app-child>

And then in the child component I have created an @Input property:

@Input() parent: FormGroup;

And then reference that input in the child template:

<div class="fields-wrap" [formGroup]="parent">
   <div class="input-wrap">
      <label>Bin ID <span>*</span><input type="text" formControlName="id"></label>
   </div>
  <div class="clearfix"></div>
</div>

In the following StackBlitz , you can click on 'edit quality' and you will see in the console the message 'Cannot find control with the name id'

I followed a tutorial for this method but can't figure out why the child component isn't seeing the form group.

I looked at your code and app-child is waiting for its own form and you are trying to inject the parent form which doesn't have the child attributes like id, type, subtype, etc.

So instead of inject the parent, just try to inject the child form that comes from your FormArray ( binsFormArray ), like this:

<app-child [parent]="binsFormArray.at(i)"></app-child>

You need to apply OnChanges on your child component to pickup the new Parent form.

Import OnChanges.

implement it export class ChildComponent implements OnInit, OnChanges {

ngOnChanges(changes) {
    console.log('changes', changes);
    this.parent = changes.parent;
}

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