Lakhvir Singh
Lakhvir Singh

Reputation: 672

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

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.

Upvotes: 13

Views: 20022

Answers (7)

tal faran
tal faran

Reputation: 127

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.

Upvotes: 3

jkufrin
jkufrin

Reputation: 21

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>

Upvotes: 0

Lakhvir Singh
Lakhvir Singh

Reputation: 672

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

Upvotes: 0

Prathmesh Dali
Prathmesh Dali

Reputation: 2350

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

Upvotes: 8

AVJT82
AVJT82

Reputation: 73357

By comments it seems that you want to just push new values to your form Array, then let's just use map for that, and push 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 you have typo, and that home_cleaning is actually an nested form group.

And for getting the value, just do:

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

Upvotes: 0

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

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

Upvotes: 8

Ketan Akbari
Ketan Akbari

Reputation: 11257

Try this:

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

            })],
        ]),
    });
}

Upvotes: 0

Related Questions