I am working on angular2 application and using angular reactive forms. How to get value of innermost element and set its value.
form : FormGroup;
constructor(private formBuilder: FormBuilder)
{
this.form = formBuilder.group({
'home_cleaning' : [{
cities : FormBuilder.array([])
}]
});
}
setValue()
{
let cities_array = [1,2,3,4];
this.form.controls['home_cleaning']['cities'].setValue(cities_array);
}
getValue()
{
console.log(this.form.controls['home_cleaning']['cities'].value);
}
Getting error in console : Cannot read property 'setValue/value' of undefined.
Try this answer
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = formBuilder.group({
'home_cleaning': formBuilder.group({
cities: [] //if you want to set values as normal array if you want to create FormArray use new FormArray([]) and push formCotrols in this array.
})
});
}
setValue() {
let cities_array = [1, 2, 3, 4];
this.form.get(['home_cleaning','cities']).setValue(cities_array);
}
getValue() {
console.log(this.form.get(['home_cleaning','cities']).value);
}
Had the same issue, solved it like this :
this.newEmployeeForm = new FormGroup({
controls..............
and nested Form:
PersonalAdress : new FormGroup({
StreetName: new FormControl(null),
StreetNumber: new FormControl(null),
ZipCode : new FormControl(null),
Region: new FormControl(null)
})
})
So I just use a Path like I would use inside my HTML code:
this.newEmployeeForm.get('PersonalAdress.StreetName').setValue(data);
Like this you can set even the deepest nesting form elements, as long as you provide the right path.
Note that I give the get method a string.
If you want to populate your form with data, you have to patch it
this.form.patchValue(dataObject);
or
this.form.patchValue({
'home_cleaning': { cities: 'value' }
});
With patchValue, you can assign values to specific controls in a FormGroup by supplying an object of key/value pairs for just the controls of interest.
you can merge the object
this.form.patchValue(Object.assign(this.form.value, youNewDataObject)));
or
this.form.patchValue(dataObj, {selfOnly: true });
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