Search code examples
angularangular-forms

Angular patchValue does not work inside a loop. Why?


To set values that I get from a server to an user form I use pathValue method, but if I do this line by line, work:


    this.userDataForm.patchValue({ 'first_name': userData['first_name'] });
    this.userDataForm.patchValue({ 'last_name': userData['last_name'] });
    this.userDataForm.patchValue({ 'address': userData['address'] });
    this.userDataForm.patchValue({ 'city': userData['city'] });
    this.userDataForm.patchValue({ 'province': userData['province'] });
    this.userDataForm.patchValue({ 'postal_code': userData['postal_code'] });
    this.userDataForm.patchValue({ 'phone': userData['phone'] });
    this.userDataForm.patchValue({ 'birthdate': userData['birthdate'] });
    this.userDataForm.patchValue({ 'card_id': userData['card_id'] });
    this.userDataForm.patchValue({ 'email': userData['email'] });    

But if I do this in a forEach, It does not work. userDataForm is a FormGroup var:

var items = ['first_name', 'last_name', 'address', 'city', 'province',
      'postal_code', 'phone', 'birthdate', 'card_id', 'email']
    items.forEach(item => {
      this.userDataForm.patchValue({ item: userData[item] });
    })

And I don't know why this happens. Any idea?


Solution

  • Just change from { item: userData[item] } to { [item]: userData[item] } to use Computed Property Names:

    var items = ['first_name', 'last_name', 'address', 'city', 'province', 'postal_code', 'phone', 'birthdate', 'card_id', 'email']
    items.forEach(item => {
      this.userDataForm.patchValue({ [item]: userData[item] });
    })
    

    To know more about Computed Property Names:-

    Though you don't need to iterate over the object's property to patch the value in the form, you can directly patch the whole object into the form:-

    this.userDataForm.patchValue(userData);