Angular2 Template Driven Sub Form Component With Validation
I have a template driven form which contains a group of inputs contained within an ngFor. I am trying to separate the 'sub group' which repeats into its own child component, but I
Solution 1:
One possible solution might be addition controls from child component to parent form as follows:
child.component.ts
@Component({
selector: 'child-component',
template: `
<div>
<input name="foo" required ngModel>
<input name="bar" required ngModel>
</div>
`
})
exportclassChildComponent {
@ViewChildren(NgModel) controls: QueryList<NgModel>;
constructor(private parentForm: NgForm) { }
ngAfterViewInit() {
this.controls.forEach((control: NgModel) => {
this.parentForm.addControl(control);
});
}
}
Solution 2:
You can use property binding and @Input for your problem which looks as
<form #parentForm="ngForm"><inputname="firstName"ngModelrequired><inputname="lastName"ngModelrequired><child-component #parentForm.childForm="ngForm" [children]="children"></child-component></form>
In your
Declare a input variable as
@Input() children:any[]=[];
Modify the template as below
<div *ngFor="let child of children;"><inputname="foo"required [(ngModel)]="child.foo"/></div>
Post a Comment for "Angular2 Template Driven Sub Form Component With Validation"