ngFor 内部的 Angular2 ngModel
Angular2 ngModel inside of ngFor
我试图从我的输入中绑定一个字符串数组,所以在 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>
但这并没有像预期的那样工作,因为当我记录单词变量时,它显示一个空数组,正如我的组件 class 中初始化的那样。此外,我记录了来自另一个组件的变量应该是我的问题的问题。我有两个组成部分:
- 包含查询组件数组的表单组件。
- 具有单词字符串数组的查询子组件。
因此,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
解决,但我不确定。
通过使用@Input() 函数并传递查询数组+ 查询索引号解决了这个问题。谢谢大家的支持。
每个输入标签都必须定义一个唯一的 'name' 属性,如以下所述:
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>
我试图从我的输入中绑定一个字符串数组,所以在 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>
但这并没有像预期的那样工作,因为当我记录单词变量时,它显示一个空数组,正如我的组件 class 中初始化的那样。此外,我记录了来自另一个组件的变量应该是我的问题的问题。我有两个组成部分:
- 包含查询组件数组的表单组件。
- 具有单词字符串数组的查询子组件。
因此,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
解决,但我不确定。
通过使用@Input() 函数并传递查询数组+ 查询索引号解决了这个问题。谢谢大家的支持。
每个输入标签都必须定义一个唯一的 'name' 属性,如以下所述:
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>