如何在[嵌套的]ngFor中设置ngModel (Angular rc2)



前提:我尝试了几个答案(包括一个我问的和意外接受的),但没有一个适合我。

我有一个嵌套的ngFor和一个嵌套的ngModel绑定。

问题:当我在嵌套的ngFor中更新一个项时,相应的项也会在另一个嵌套的ngFor中更新。

模板

<div *ngFor="let outerObject of outerObjects; let oIndex = index; trackBy: trackByIndex">
    {{outerObject.value}} <!-- this works -->
    <div *ngFor="let innerObject of outerObject.innerObjects; let index = index; trackBy: trackByIndex">
          <input [(ngModel)]="outerObject.innerObjects[index]"> <!-- when I change this any innerObjects[i] is updated -->
    </div>
</div>

ts

outerObjects = [
    {
       value = 'x'
       innerObjects: ['a', 'b', 'c']
    },
    {
       value = 'y'
       innerObjects: ['a', 'b', 'c']
    }
];
trackByIndex(index: number, obj: any): any {
    return index;
}

你有一个语法错误:你必须写[(ngModel)]而不是[(ngModel])(注意末尾的方括号和普通括号的顺序)

在纠正了语法错误并在Angular 2.1.1中运行你的代码后,它似乎可以工作了。只绑定到对应的outerObject.innerObjects[index]

最新更新