How to get and set value in fields of nested form in angular2?

I am working on an angular2 application and using angular reactive forms. How to get the value of the 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 an error in the console: it is not possible to read the setValue / value property from undefined.

+5
source share
4 answers

If you want to fill out a form with data, you must correct 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, providing an object of key / value pairs for all interest control.

you can combine the object

 this.form.patchValue(Object.assign(this.form.value, youNewDataObject))); 

or

 this.form.patchValue(dataObj, {selfOnly: true }); 
+1
source

Try the following:

  setValue() { let cities_array = [1, 2, 3, 4]; this.form = this.formBuilder.group({ home_cleaning: this.formBuilder.array([ [({ cities: cities_array, })], ]), }); } 
0
source

According to the comments, it seems that you just want to click the new values ​​in your Array form, and then just use map to do this and click on the new form controls:

 setValue() { let cities_array = [1,2,3,4]; let arr = this.form.get('home_cleaning.cities').controls; cities_array.map(city => arr.push(new FormControl(city))) } 

PS. Here, I assume that you have a typo, and that home_cleaning is actually a nested form group.

And to get the value just do:

 this.form.get('home_cleaning.cities').value 
0
source

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); } 
0
source

Source: https://habr.com/ru/post/1269942/


All Articles