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 implement it with ControlValueAccessor but want to start with simple @input form group.
@Component({
selector: 'my-child',
template: `
<h1>Child</h1>
<div [formGroup]="childForm">
<input formControlName="firstName">
<input formControlName="lastName">
</div>
`
})
export class Child {
@Input()
childForm: FormGroup;
}
What you want to do can be achieved more easily without implementing ControlValueAccessor. Instead, you can simply set the viewProviders in the child component to use the existing parent NgForm as the ControlContainer.
Then, there's no need to pass the form/formGroup as an input parameter to the child component as the form controls will automatically be part of the parent's form.
child.component.ts:
input-child.component.html:
parent.component.html:
I don't know why the question was down voted, but I feel it may be helpful to other So I am posting the answer. After multiple attempts to bind child's formgroup I was able to successfully bind value
http://plnkr.co/edit/ldhPf7LTFVtTFHe9zfAj?p=preview
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
we initialize username as a FormGroup instead of a control:
In the child component we need a Input Property for the 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