[英]Angular 2 - 2 Way Binding with NgModel in NgFor
在 Angular 2 中,如何使用 NgFor 在重復列表中與 NgModel 進行 2 路綁定。 下面是我的 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 和下面的代碼。 希望這對其他人有幫助。
@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;
}
}
由於兩個原因,您所做的工作不起作用。
這是您問題的有效解決方案。
<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>
嘗試這個
@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() {
}
}
您必須使用 name + index 將 name 屬性添加到 ngModel 以使其唯一。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.