[英]Angular2 ngModel inside of ngFor
I am trying to bind an array of strings from my inputs, so in the html file I wrote this: 我试图从我的输入绑定一个字符串数组,所以在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>
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. 但是这没有按预期工作,因为当我记录单词变量时,它显示在我的Component类中初始化的空数组。 Also, I log the variable from another component should that supposed to be the issue for my problem. 另外,我应该记录来自另一个组件的变量应该是我的问题的问题。 I have two components: 我有两个组成部分:
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: 虽然查询是表单组件中的Query数组:
queries:Query[] = [];
Thanks for your help! 谢谢你的帮助!
The problem is with using an array of primitive values ( words
) in ngFor
. 问题是在ngFor
使用原始值( words
) 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. 使用trackBy
也可以解决trackBy
但我不确定。
Each input tag has to have a unique 'name' attribute defined, as described in: 每个输入标记都必须定义一个唯一的“名称”属性,如下所述:
Angular2 ngModel inside ngFor (Data not binding on input) ngFor中的Angular2 ngModel(数据不绑定输入)
Here is the corrected code: 这是更正后的代码:
<div *ngFor="let word of words; let in=index" class="col-sm-3">
<div class="form-group">
<input type="text" [(ngModel)]="words[in]" name="word{{in}}" class="form-control" [attr.placeholder]="items[in]" required>
</div>
Solved this by using the @Input() function and passing the queries array + the query index number. 通过使用@Input()函数并传递查询数组+查询索引号来解决这个问题。 Thank you guys for the support. 谢谢你们的支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.