I came across Kara Erickson's demo of Angular forms at AngularConnect 2017, on YouTube. The part I'm specifically interested is where she describes nested reactive forms
I've done everything as Kara describes, but I end up getting a null
parentForm no matter what I try.
I've reproduced a simplified version of my code below. The problem is that in the child-form
component I am getting null
.
// PARENT COMPONENT
@Component({
selector: 'parent-form',
styleUrls: ['./parent-form.component.css'],
template: `
<form [formGroup]="createAlbumProfileForm" (ngSubmit)="onFormSubmitted($event)">
<input type="text" placeholder="Something unique to parent form"/>
<child-form></child-form>
</form>
`
})
export class ParentFormComponent implements OnInit {
parentForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.parentForm = this.formBuilder.group({
yoloField: this.formBuilder.control('')
});
}
// CHILD COMPONENT
@Component({
selector: 'child-form',
styleUrls: [ './child-form.component.scss' ],
viewProviders:[ { provide: ControlContainer, useExisting: FormGroupDirective } ],
template: `
<div formGroupName="songName" class="form-group"></div
`
})
export class ChildFormComponent implements OnInit {
childForm: FormGroup;
constructor(private parentForm: FormGroupDirective) {
this.childForm = parentForm.form; // null
}
}
It seems like it is problem with life cycle of the components: in video FormGroup
is initialized in constructor of parent component but in your example you initialize it OnInit
. The problem is that child's constructor is called before parent's OnInit
that is why you are getting null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With