I\'m trying achieve a nested form with validation in Angular 2, I\'ve seen posts and followed the documentation but I\'m really struggling, hope you can point me in the right di
An alternative to the FormGroupDirective
(as described in @blacksheep's answer) is the use of ControlContainer
like so:
import { FormGroup, ControlContainer } from "@angular/forms";
export class ChildComponent implements OnInit {
formGroup: FormGroup;
constructor(private controlContainer: ControlContainer) {}
ngOnInit() {
this.formGroup = this.controlContainer.control;
}
The formGroup
can be set in the direct parent or further up (parent's parent, for example). This makes it possible to pass a from group over various nested components, without the need for a chain of @Input()
s to pass the formGroup along. In any parent set the formGroup
to make it available via ControlContainer
in the child:
<... [formGroup]="myFormGroup">