我正在尝试从输入中绑定一个字符串数组,所以在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>
但这并没有像预期的那样工作,因为当我记录单词变量时,它会在我的Component类中初始化时显示一个空数组。另外,我应该记录来自另一个组件的变量应该是我的问题的问题。我有两个组成部分:
因此,单词变量被声明到查询组件中,但我通过表单组件记录此变量,如下所示:
console.log(JSON.stringify(this.queries));
虽然查询是表单组件中的Query数组:
queries:Query[] = [];
感谢您的帮助!
答案 0 :(得分:16)
问题是在words
中使用原始值数组(ngFor
)。
您可以将单词更改为对象数组,例如
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
也可以解决这个问题,但我不确定。
答案 1 :(得分:13)
每个输入标记都必须定义一个唯一的“名称”属性,如下所述:
Angular2 ngModel inside ngFor (Data not binding on input)
以下是更正后的代码:
<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>
答案 2 :(得分:1)
通过使用@Input()函数并传递查询数组+查询索引号来解决这个问题。谢谢大家的支持。