简体   繁体   English

ngModel不会更新更改值

[英]ngModel does not update value on change

I have ngModel, inside ngFor loop: 我在ngFor循环中有ngModel:

<div *ngFor="let comment of comments">
   <div *ngFor="let answer of toArray(comment.answers); let j = index; trackBy: trackByIndex;">
      <textarea id="editAnswer[j]" name="editAnswer[j]" [(ngModel)]="answer.text">

      {{ answer.text }}
   </div>
</div>

In my component i have two functions for index iterate and convert object to array: 在我的组件中,我有两个函数用于索引迭代并将对象转换为数组:

  trackByIndex(index: number, obj: any): any {
    return index;
  }

  toArray(answers: object) {
    return Object.keys(answers).map(key => ({
      key,
      ...answers[key]
    }))
  }

But when i change text what was binded in textarea, ngModel does not change. 但是当我更改文本在textarea中绑定的内容时,ngModel不会更改。

Stackblitz example: https://stackblitz.com/edit/angular-z6xatv Stackblitz示例: https ://stackblitz.com/edit/angular-z6xatv

The toArray method appears to be creating a copy of the original comments.answers.text values. toArray方法似乎正在创建原始comments.answers.text值的副本。 When the text property is modified in the input elements, the change does not affect the original data (the console in this stackblitz shows that the values are not shared). 在输入元素中修改text属性时,更改不会影响原始数据( 此stackblitz中的控制台显示不共享值)。

If you simplify toArray so that it returns a simple array of the answers , the code works (see this stackblitz ). 如果你简化toArray以便它返回一个简单的answers数组,代码就可以了(参见这个stackblitz )。 The items in the array share the same text references as the original data. 数组中的项与原始数据共享相同的text引用。

comments = [
  {
    text: 'dsddsdsd', answers: {
      FszW: { text: 'answer 1' },
      dsSce: { text: 'answer 2' }
    }
  }
]

toArray(answers: object) {
  return Object.keys(answers).map(key => answers[key]);
}

If you need an access to the key, you can use this version of toArray : 如果您需要访问密钥,可以使用此版本的toArray

toArray(answers: object) {
  return Object.keys(answers).map(key => {
    return { key: key, value: answers[key] };
  });
}

with the following template markup: 使用以下模板标记:

<textarea name="answer_{{j}}" [(ngModel)]="answer.value.text"></textarea>
{{ answer.key }}: {{ answer.value.text }}

As a side note, I suggest setting the name property in the template with one of the following syntaxes: 作为旁注,我建议使用以下语法之一在模板中设置name属性:

name="answer_{{j}}"
[name]="'answer_' + j"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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