angular 2 form level validation using components

后端 未结 2 914
生来不讨喜
生来不讨喜 2020-12-30 11:27

In Angular 2 how do you add an input control in a custom component that will bind to the form control container in the parent component? (FOLLOWING CODE SIMPLIFIED FOR BREVI

2条回答
  •  梦谈多话
    2020-12-30 11:47

    Not sure if this is the best way for your scenario, but I think it works.

    You can create the Control on the parent element and pass it as @Input to the child. The child can then use it as the control on the form element.

    For example (plunk):

    @Component({
      selector:'my-special-input'
      template:`
             
        `
    })
    export class specialInputComponent implements OnInit{
      @Input() nameControl;
    }
    
    @Component({
      selector:'my-form',
      template:`
        
    `, directives: [specialInputComponent] }) export class formComponent{ nameControl:Control; myForm: ControlGroup; constructor(){ this.nameControl = new Control("", Validators.required ); this.myForm = new ControlGroup({special: this.nameControl}); } }

    You could probably also pass the ControlGroup to the child and let the child add itself with addControl() but you might have to deal with the update cycle getting a little messy.

提交回复
热议问题