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

Viewed 15364

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.

7 Answers

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.

    form : FormGroup;

    constructor(private formBuilder: FormBuilder)
    {
       this.form = this.formBuilder.group({
          'home_cleaning' : this.formBuilder.array([
             this.formBuilder.group({
                cities : this.formBuilder.array([])
             })
          ])
       });
    }

   setValue()
   {
      let cities_array = [1,2,3,4];
      (this.form.controls['home_cleaning'].value).forEach((value, key)=> {
         let citiesArray = <FormArray>(<FormArray>this.form.controls['home_cleaning']).controls[key].get('cities');
         for(let city of cities_array){
            citiesArray.push(new FormControl(city))
         }
      });
      this.getValue();
   }

   getValue()
   {
      (this.form.controls['home_cleaning'].value).forEach((value, key)=> {
         let citiesArray = <FormArray>(<FormArray>this.form.controls['home_cleaning']).controls[key].get('cities').value;
      });
   }

I was trying to do something similar and found this pattern worked well in the template:

<span class="label-error" *ngIf="(form.controls['parentControl'].controls['childControl'].invalid && attemptedSubmit)">Please select childControl.</span>
Related