Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 form level validation using components

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 BREVITY)

For example, I have a form component (please note the button disabled binding)

@Component{
selector:'my-form',
template:'
<form [ng-form-model]="myForm">
    <my-special-input></my-special-input>
</form>
<button [disabled]="!myForm.valid">
'
}

Now in my special input component I would like to

@component{
 selector:'my-special-input'
 template:'
    <input ng-control='name' required>
}'

ng-control='name' generates an error "No provider for ControlContainer!" I have searched for solutions and haven't found any that would allow for parent form control container validation.

I would think creating custom reusable input components that get added to a form control container would be a common scenario in Angular 2.

I cant image there there is no way add the input in the custom component to the parent form component in a way that would enable form level validation.

like image 520
JeffC Avatar asked Jan 24 '16 19:01

JeffC


1 Answers

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.

like image 195
Mark Avatar answered Oct 19 '22 07:10

Mark