angular 2 form level validation using components

后端 未结 2 898
生来不讨喜
生来不讨喜 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:`
            <input type="text" [ngFormControl]='nameControl' > 
        `
    })
    export class specialInputComponent implements OnInit{
      @Input() nameControl;
    }
    
    @Component({
      selector:'my-form',
      template:`
        <form [ngFormModel]="myForm" >
           <my-special-input [nameControl]="nameControl"></my-special-input>
        </form>
        <button [disabled]="!myForm.valid">Submit</button>
        `,
        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.

    0 讨论(0)
  • 2020-12-30 12:03

    Form validation with Angular couples the validation with the component.

    This leads to the business logic around validation being scattered all over the application in components.

    Many times it is better to create a TypeScript based re-usable validation service.

    • This allows the business logic to be centralized in one place.

    • You can unit test this business logic by unit testing the service.

    This demo Angular 6 CLI app shows you how to do this.

    https://github.com/VeritasSoftware/ts-validator-app-angular6

    You might find this useful from your design considerations.

    0 讨论(0)
提交回复
热议问题