Dividing a form into multiple components with validation

后端 未结 4 1243
闹比i
闹比i 2020-12-23 11:19

I want to create a single big form with angular 2. But I want to create this form with multiple components as the following example shows.

App component

4条回答
  •  执念已碎
    2020-12-23 11:45

    I'd like to share approach that did the job in my case. I've created following directive:

    import { Directive } from '@angular/core';
    import { ControlContainer, NgForm } from '@angular/forms';
    
    @Directive({
      selector: '[appUseParentForm]',
      providers: [
        {
          provide: ControlContainer,
          useFactory: function (form: NgForm) {
            return form;
          },
          deps: [NgForm]
        }
      ]
    })
    export class UseParentFormDirective {
    }
    

    Now, if you use this directive on child component, for example:

    controls from AddressComponent will be added to form1. As a result form validity will also depend on state of controls inside child component.

    Checked only with Angular 6

提交回复
热议问题