'Nested FormGroupDirective in child components
There is a problem with FormGroupDirective dependency injection. I have an example of relation component to each other:
<app-component-group>
<child-group>
<child-control></child-control>
</child-group>
</app-component-group>
There I have FormGroup in the parent component,
in the first child component - nested FormGroup, and in the last child control component - nested FormControl.
Code is simple:
child-group.ts
...
constructor(private parentForm: FormGroupDirective) { }
ngOnInit() {
this.parentForm.form.addControl('group', new FormGroup({}));
}
...
child-control.ts
...
constructor(private parentForm: FormGroupDirective) { }
ngOnInit() {
this.parentForm.form.addControl('testControl', new FormControl());
}
...
But here I got the problem!
Injector for FormGroupDirective is relative to the root element (app-component-group). And I got wrong result: formGroup: { group: {}, control } instead of what I need: formGroup: { group: { control } }.
Solution 1:[1]
You have to add this in child.component.ts
viewProviders: [
{ provide: ControlContainer, useExisting: FormGroupDirective },
]
example: https://stackblitz.com/edit/angular-ivy-qpaihe?file=src%2Fapp%2Fchild%2Fchild.component.ts
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jona303 |
