I have a FormGroup, nested in another FormGroup, where I want to get a certain control with get().
I tried the following solution, which doesn't work:
formGroup.get('formGroupKey').get('formControlKey');
But this throws an error. The first get() works (and correctly returns a FormGroup), but the second get throws an exception (path.split is not a function)
Any idea how I can solve that?
@Update
I solved it now this way (which is not a pretty solution though):
formGroup.get(tab.id)['controls'][segment.id];
With a parent FormGroup, the name input needs the syntax formControlName=name in order to be associated with the correct FormControl in the class. This syntax tells Angular to look for the parent FormGroup, in this case heroForm, and then inside that group to look for a FormControl called name.
FormControlNamelinkSyncs a FormControl in an existing FormGroup to a form control element by name.
To fetch the value of a form control, we have to use value property on the instance of FormControl in our class. In the same way we can fetch the value in HTML template. city = new FormControl('Noida'); console. log(this.
This should work: this.formGroup.get(varibaleKey).get(variableKey2)
Here is some code:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular 5';
form: FormGroup;
key1: string = 'test1';
key2: string = 'test2';
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
test1: this.formBuilder.group({
test2: ['testValue']
}),
another: ['testValue']
});
console.log(this.form.get(this.key1).get(this.key2));
}
}
Here is an example: https://stackblitz.com/edit/angular-ipman8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With