Angular 2 nested forms with child components and validation

后端 未结 6 1258
醉话见心
醉话见心 2021-02-05 13:16

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

6条回答
  •  迷失自我
    2021-02-05 13:33

    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">
    

提交回复
热议问题