Angular 2 - 在 NgFor 中使用 NgModel 的 2 种方式绑定(bind)

标签 angular typescript

在 Angular 2 中,我如何使用 NgFor 在重复列表中获得与 NgModel 的双向绑定(bind)。以下是我的 plunkr 和代码,但出现错误。

Plunkr

@Component({
  selector: 'my-app',
  template: `
  <div>
    <div *ngFor="let item of toDos;let index = index;">
      <input [(ngModel)]="item" placeholder="item">
    </div>
    Below Should be binded to above input box
    <div *ngFor="let item of toDos">
      <label>{{item}}</label>
    </div>
  </div>
  `,
  directives: [MdButton, MdInput]
})
export class AppComponent { 
  toDos: string[] =["Todo1","Todo2","Todo3"];
  constructor() {}
  ngOnInit() {
  }
}

最佳答案

在深入研究之后,我需要在 ngFor 上使用 trackBy。更新了下面的 plnkr 和代码。

Working Plnkr

@Component({
  selector: 'my-app',
  template: `
  <div>
    <div *ngFor="let item of toDos;let index = index;trackBy:trackByIndex;">
      <input [(ngModel)]="toDos[index]" placeholder="item">
    </div>
    Below Should be binded to above input box
    <div *ngFor="let item of toDos">
      <label>{{item}}</label>
    </div>
  </div>
  `,
  directives: [MdButton, MdInput]
})
export class AppComponent { 
  toDos: string[] =["Todo1","Todo2","Todo3"];
  constructor() {}
  ngOnInit() {
  }
  trackByIndex(index: number, obj: any): any {
    return index;
  }
}

关于Angular 2 - 在 NgFor 中使用 NgModel 的 2 种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40314732/

相关文章:

typescript - 如何从泛型函数中的参数类型推断返回类型?

razor - 在 cshtml 文件中使用 TypeScript

ios - 来自外部 url 的 Ionic 5 电容器/Angular 预览文件

javascript - Angular 中的距离计算

typescript - Angular2 canActivate() 调用异步函数

angular - 如何在Ionic中实现搜索和过滤

angular - 如何在 Angular2 中追加/更新查询参数

reactjs - 当使用 React Component 作为参数时为 "Type is missing the following properties, context, setState"

angular - 安全错误 : Failed to execute 'replaceState' on 'History' :

validation - 将输入类型编号限制为 Angular 2 中的小数点后 2 位