Issue
I have a component MyForm that has HTML like this
<form [formGroup]="myFormGroup">
<app-my-input-component></app-my-input-component>
</form>
And in the MyInputComponent the html is
<input formControlName='myInput'>
When I do this, I get the error formControlName must be used with a parent formGroup directive
Is there any way to get this sort of structure to work with formGroups, or should I move everything into one component?
Solution
You can use the ControlContainer
to enable the form to be split up into multiple components.
import { Component, Input } from '@angular/core';
import {
ControlContainer,
FormGroupDirective,
FormControl,
Validators,
} from '@angular/forms';
@Component({
selector: 'my-form-child',
template: `<input [formControlName]="controlName">`,
viewProviders: [
{
provide: ControlContainer,
useExisting: FormGroupDirective,
},
],
})
export class ChildComponent {
@Input() controlName: string;
constructor(private parent: FormGroupDirective) {}
ngOnInit() {
this.parent.form.addControl(
'age',
new FormControl('', Validators.required)
);
}
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.