Reputation: 470
I'm surprised that I have not come across a question asking about how to point to a FormGroup that is nested within another FormGroup. It becomes an eyesore and tedious when you continue to refer to nested form groups in this manner to access an object within it.
<FromGroup>.controls['FormGroupName'].controls['FormGroupName]...etc.
Is there any way to point to a nested form group in the typescript file and then use that new variable in place of it's eyesore alternative?
I have tried the following:
parentForm: FormGroup;
nestedForm: FormGroup;
...
// 1.
nestedForm = this.parentForm.get('nestedFormName')
// 2.
nestedForm = this.parentForm.controls['nestedFormName']
Both of the examples above do not work as it returns an error about AbstractControls.
Upvotes: 1
Views: 1047
Reputation: 691695
'AbstractControl' cannot be assigned to type 'FormGroup'. Property 'controls' is missing from type 'AbstractControl'. I was under the impression that FormGroup, FormControls, and FormArray are all Abstract controls.
That means that TypeScript doesn't agree to assign the value returned by this.parentForm.get('nestedFormName')
to a variable of type FormGroup
. The reason is stated in the error: since the method return type is AbstractControl
, TypeScript can't possibly know that what is actually returned is a FormGroup
. It could be a FormGroup. But it could also be something else (a FormControl, or a FormArray, for example). You know that, but the compiler does not. So you have to tell the compiler, using a type assertion, that you know that the returned AbstractControl is indeed a FormGroup
:
nestedForm = this.parentForm.get('nestedFormName') as FormGroup;
To take a simpler example, let's say you have FruitBasket class, and you ask it to get the Fruit at some position in the basket.
You can of course do that:
const fruit: Fruit = basket.get(i);
But you can't do that:
const banana: Banana = basket.get(i);
because TypeScript doesn't know if the fruit at position i is a Banana, or an Apple, or a Pear. It could be any of those. So, if you know that a banana is at position i, then you need to tell TypeScript:
const banana: Banana = basket.get(i) as Banana;
Upvotes: 1
Reputation: 470
My scope of solutions was very much limited to just typescript. Looking at other example across the web and on angular's website it illustrates using 'formGroupName' to refer to areas in the HTML that deal with a nested formGroup controls.
Upvotes: 1