ControlValueAccessor with multiple formControl in child component

前端 未结 3 529
死守一世寂寞
死守一世寂寞 2020-12-30 03:15

I have multiple formcontrols in the child component, how to apply validators in the child component, So that original form will become invalid. It would be ideal to implemen

3条回答
  •  悲&欢浪女
    2020-12-30 03:40

    At first, this helped me a lot, but then I found out, that we're over-complicating things. We do not have to build our own formControl, we can just pass the formGroup to our child component. In the parent component, instead of

    this.form = fb.group({
      name:['Angular2 (Release Candidate!)'],
      username: [{firstName: 'First', lastName: 'Last'}],
      email:['My Email']  
    });
    

    we initialize username as a FormGroup instead of a control:

    this.form = fb.group({
      name:['Angular2 (Release Candidate!)'],
      username: fb.group({
       firstName: ['First'],
       lastName: ['Last']
      }),
      email:['My Email']
    });
    

    In the child component we need a Input Property for the FormGroup

    @Input()
    usernameGroup: FormGroup;
    

    In the child template:

    and then in the parent template:

    
    

    For more information, check out this post: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2

    Building your own formControl is really an overkill here, for more information about that, have a look here: http://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

提交回复
热议问题