在 NgFor 中使用 NgModel 进行 Angular 2 - 2 方式绑定 [英] Angular 2 - 2 Way Binding with NgModel in NgFor

查看:30
本文介绍了在 NgFor 中使用 NgModel 进行 Angular 2 - 2 方式绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 2 中,如何使用 NgFor 在重复列表中与 NgModel 进行 2 路绑定.下面是我的 plunkr 和代码,但出现错误.

Plunkr

@Component({选择器:'我的应用',模板:`<div><div *ngFor="let item of toDos;let index = index;"><input [(ngModel)]="item" placeholder="item">

下面应该绑定到上面的输入框<div *ngFor="let item of toDos"><label>{{item}}</label>

`,指令:[MdButton, MdInput]})导出类 AppComponent {toDos: string[] =["Todo1","Todo2","Todo3"];构造函数(){}ngOnInit() {}}

解决方案

在挖掘之后我需要在 ngFor 上使用 trackBy.更新了 plnkr 和下面的代码.希望这对其他人有帮助.

工作 Plnkr

@Component({选择器:'我的应用',模板:`<div><div *ngFor="let item of toDos;let index = index;trackBy:trackByIndex;"><input [(ngModel)]="toDos[index]" placeholder="item">

下面应该绑定到上面的输入框<div *ngFor="let item of toDos"><label>{{item}}</label>

`,指令:[MdButton, MdInput]})导出类 AppComponent {toDos: string[] =["Todo1","Todo2","Todo3"];构造函数(){}ngOnInit() {}trackByIndex(index: number, obj: any): any {回报指数;}}

In Angular 2 how would I get 2 way binding with NgModel within a repeating list using NgFor. Below is my plunkr and code but I get an error.

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() {
  }
}

解决方案

After digging around I need to use trackBy on ngFor. Updated plnkr and code below. Hope this helps others.

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

这篇关于在 NgFor 中使用 NgModel 进行 Angular 2 - 2 方式绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆