Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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.

like image 578
Lakhvir Singh Avatar asked Jul 18 '17 12:07

Lakhvir Singh


3 Answers

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);
}
like image 130
Prathmesh Dali Avatar answered Nov 13 '22 18:11

Prathmesh Dali


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.

like image 38
tal faran Avatar answered Nov 13 '22 18:11

tal faran


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 });
like image 6
Yordan Nikolov Avatar answered Nov 13 '22 18:11

Yordan Nikolov