我试图从我的输入中绑定(bind)一个字符串数组,所以在 html 文件中我这样写:
<div *ngFor="let word of words; let in=index" class="col-sm-3">
<div class="form-group">
<input type="text" [(ngModel)]="words[in]" class="form-control" [attr.placeholder]="items[in]" required>
</div>
</div>
但这并没有按预期工作,因为当我记录 words 变量时,它显示一个空数组,如我的 Component 类中初始化的那样。此外,我记录了来自另一个组件的变量应该是我的问题的问题。我有两个组件:
- 包含查询组件数组的表单组件。
- 具有单词字符串数组的查询子组件。
因此,words 变量已声明到查询组件中,但我通过表单组件记录此变量,如下所示:
console.log(JSON.stringify(this.queries));
虽然queries是表单组件中的一个Query数组:
queries:Query[] = [];
感谢您的帮助!
最佳答案
问题在于在 ngFor
中使用原始值数组(words
)。
您可以将单词更改为对象数组,例如
words = [{value: 'word1'}, {value: 'word2'}, {value: 'word3'}];
像这样使用它
<div *ngFor="let word of words; let in=index" class="col-sm-3">
<div class="form-group">
<input type="text" [(ngModel)]="words[in].value" class="form-control" [attr.placeholder]="items[in]" required>
</div>
</div>
这也可以使用 trackBy
解决,但我不确定。
关于data-binding - ngFor 内部的 Angular2 ngModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423663/