NgFor中与NgModel的Angular 2 - 2路绑定

Ka *_*ech 45 typescript angular

在Angular 2中,如何使用NgFor在重复列表中与NgModel进行双向绑定.下面是我的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() {
  }
}
Run Code Online (Sandbox Code Playgroud)

Ka *_*ech 75

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

工作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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上`trackBy`在你的代码中并不重要!重要的是`[(ngModel)] ="toDos [index]"`而不是`[(ngModel)] ="item"` (22认同)
  • @Lars没有trackBy输入失去焦点,似乎挂在我的经验. (15认同)
  • 没有trackBy`ngFor`每次更改数组中的字符串时都会重新创建DOM,所以这是完全必要的. (12认同)

Las*_*apa 37

由于两个原因,你所做的不起作用.

  • 您必须使用toDos [index]而不是使用ngModel的项目(阅读更多信息)
  • 每个输入都必须具有唯一的名称

这是您的问题的可行解决方案.

<div>
<div *ngFor="let item of toDos;let index = index;">
  <input name=a{{index}} [(ngModel)]="toDos[index]" placeholder="item">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
  <label>{{item}}</label>
</div>
Run Code Online (Sandbox Code Playgroud)

  • “每个输入都必须有一个唯一的名称” - 这救了我。谢啦 (3认同)
  • 我搜索了多个问题,直到从这个问题中得到答案。我的问题是“每个输入必须具有唯一的名称”。这正是我所需要的! (2认同)