Reputation: 319
I have a component that takes FormGroup as @Input.
parentComponent:
parentGroup = fb.group({
childGroup: fb.group({
nestedControl: fb.control([])
})
})
<app-my-component [formGroup]="myGroup">
Then in the child component I have:
@Input formGroup: FormGroup
<div *ngIf="formGroup.controls.childGroup.controls.nestedControl === true">
some content
</div>
I get an error
error TS2339: Property 'controls' does not exist on type 'AbstractControl'.
I guess the child control does not know the structure of formGroup input. How do I typecast AbstractControl to FormGroup within the template? I guess I can make a function that casts in the .ts file and returns formGroup, but that seems cumbersome. Any way to do it in the template? any other clever solutions? :)
Upvotes: 2
Views: 1254
Reputation: 73357
In the child component that error actually points to your nested group. Angular does not know that childGroup
is a FormGroup. I don't see why you couldn't just send the child the nested FormGroup instead of the whole form. First of all your code becomes shorter in template as you don't need to traverse downwards, secondly, that error gets fixed as you can type that childGroup
is a FormGroup :)
parent:
<app-my-component [formGroup]="myGroup.get('childGroup')">
and child:
@Input() formGroup: FormGroup;
<div *ngIf="formGroup.get('nestedControl') === true">
some content
</div>
Notice I also used get
. I prefer that myself :)
EDIT: If you need to pass the parent formgroup, you can access nested propertied just like we use in JS objects, i.e using .
:
<div *ngIf="formGroup.get('childGroup.nestedControl').value === true">
Upvotes: 1