Angular 8: formControlName inside component multiple nested levels below
You can consider four options:
1) provide ControlContainer on your component with FormControlName
d.component.ts
@Component({
...
viewProviders: [
{
provide: ControlContainer,
useExisting: FormGroupDirective
}
]
})
export class DComponent implements OnInit {
Ng-run Example
2) create simple directive that provides ControlContainer
@Directive({
selector: '[provideContainer]',
providers: [
{
provide: ControlContainer,
useExisting: FormGroupDirective
}
]
})
export class ProvideContainerDirective {
}
then place this directive somewhere at the top of nodes hierarchy in your
d.component.html
<ng-container provideContainer>
<input formControlName="someName">
</ng-container>
Ng-run Example
3) use FormControlDirective instead of FormControlName directive
FormControlDirective requires FormControl instance to be passed
<input [formControl]="control">
You can get this instance either though DI:
d.component.ts
export class DComponent implements OnInit {
control;
constructor(private parentFormGroupDir: FormGroupDirective) { }
ngOnInit() {
this.control = this.parentFormGroupDir.control.get('someName');
}
Ng-run Example
or use some service that ties your components.
d.component.ts
export class DComponent implements OnInit {
control: FormControl;
constructor(private formService: FormService) { }
ngOnInit() {
this.control = this.formService.get('someName');
}
Ng-run Example
4) pass FormGroup as Input props down to the children or get it through DI or service and then wrap your input[formControlName] with formGroup directive
d.component.html
<ng-container [formGroup]="formGroup">
<input formControlName="..."
</ng-container>
Ng-run Example