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

时间:2016-10-29 00:06:44

标签: angular typescript

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

4 个答案:

答案 0 :(得分:65)

在挖掘之后,我需要在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;
  }
}

答案 1 :(得分:29)

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

  • 您必须使用toDos [index]而不是使用ngModel(Read for more info
  • 的项目
  • 每个输入都必须具有唯一名称

这是解决问题的有效方法。

        ambariRestClientConfig.host=127.0.0.1
        ambariRestClientConfig.port=8080
        ambariRestClientConfig.username=admin
        ambariRestClientConfig.password=admin
        ambari.services.status=HDFS,HIVE,MAPREDUCE2,SQOOP

答案 2 :(得分:0)

您必须使用 name + index 向 ngModel 添加 name 属性以使其唯一。

<mat-form-field
  #fileNameRef
  appearance="fill"
  color="primary"
  floatLabel="auto"
>
  <input
    matInput
    #fileNameCtrl="ngModel"
    name="originalName{{ index }}"
    [(ngModel)]="file.originalName"
    type="text"
    autocomplete="off"
    autocapitalize="off"
    readonly
  /> 
</mat-form-field>

答案 3 :(得分:-1)

尝试一下

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