13

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.

1
  • May be you have a typo in setVlaue --> setValue Commented Jul 18, 2017 at 12:12

7 Answers 7

8

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 });
Sign up to request clarification or add additional context in comments.

1 Comment

I have implemented this but getting one problem that if I have more then one field in home_cleaning field then patch value will over write all fields.
8

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

Comments

3

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.

Comments

0

Try this:

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

            })],
        ]),
    });
}

Comments

0

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

Comments

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.