ngFor 中的 Angular2 ngModel [英] Angular2 ngModel inside of ngFor
问题描述
我试图从我的输入绑定一个字符串数组,所以在 html 文件中我写了这个:
<div class="form-group"><input type="text" [(ngModel)]="words[in]" class="form-control" [attr.placeholder]="items[in]" required>
但这并没有像预期的那样工作,因为当我记录 words 变量时,它显示了一个在我的 Component 类中初始化的空数组.此外,如果应该是我的问题的问题,我会记录来自另一个组件的变量.我有两个组件:
- 包含查询组件数组的表单组件.
- 具有单词字符串数组的查询子组件.
因此, words 变量被声明到查询组件中,但我正在通过表单组件记录此变量,如下所示:
console.log(JSON.stringify(this.queries));
而查询是表单组件中的查询数组:
queries:Query[] = [];
感谢您的帮助!
问题在于在 ngFor
中使用原始值数组 (words
).
您可以将单词更改为对象数组,例如
words = [{value: 'word1'}, {value: 'word2'}, {value: 'word3'}];
并像使用它一样
<div class="form-group"><input type="text" [(ngModel)]="words[in].value" class="form-control" [attr.placeholder]="items[in]" required>
这也可以使用 trackBy
解决,但我不确定.
I am trying to bind an array of strings from my inputs, so in the html file I wrote this:
<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>
But this didn't work as expected because when I log the words variable it show an empty array as initialized in my Component class. Also, I log the variable from another component should that supposed to be the issue for my problem. I have two components:
- The form component that contains an array of query components.
- The query child component that has an array of words strings.
So, the words variable is declared into the queries component but I am logging this variable through the form component like this:
console.log(JSON.stringify(this.queries));
While queries is an array of Query in the form component:
queries:Query[] = [];
Thanks for your help!
The problem is with using an array of primitive values (words
) in ngFor
.
You can change words to an array of objects like
words = [{value: 'word1'}, {value: 'word2'}, {value: 'word3'}];
and use it like
<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>
This might also be solvable using trackBy
but I'm not sure.
这篇关于ngFor 中的 Angular2 ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!