ngFor内的Angular2 ngModel [英] Angular2 ngModel inside of ngFor

查看:64
本文介绍了ngFor内的Angular2 ngModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从输入中绑定字符串数组,所以在html文件中我这样写:

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>

但这并没有按预期工作,因为当我记录单词variables时,它显示一个空数组为在我的Component类中初始化。另外,如果我的问题出在那儿,我将从另一个组件中记录变量。我有两个组件:

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:


  • 包含查询组件数组的表单组件。

  • 具有子字符串数组的子查询组件。

因此,words变量已声明到querys组件中,但我正在记录此内容通过如下形式的表单组件变量:

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[] = [];

感谢您的帮助!

推荐答案

问题在于在 ngFor 中使用原始值(单词)数组。

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'}];

并像这样使用它

  <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 也可以解决此问题,但是我不确定。

This might also be solvable using trackBy but I'm not sure.

这篇关于ngFor内的Angular2 ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆