简体   繁体   中英

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?

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

因为item没有解析为迭代器变量,而是作为对象构造中的普通键受到威胁。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM