Angular2 ngModel 双向绑定不起作用



我想通过ngModelngFor循环中的模型绑定到输入字段,但是如果我将另一个项目添加到我的列表中,模型的值将在模型中可见,但在视图中不可见。

<div *ngFor="let model of models">
<input [(ngModel)]="model.foo" name="foo">
{{model | json}}
</div>
<button (click)="addEmptyListItem()">add</button>

如果我在视图中输入barmodel | json将显示{ 'foo': 'bar' },现在如果我将另一个元素添加到列表中,model | json仍然会显示{ 'foo': 'bar' },但在输入字段中没有任何可见内容。

我的models变量来自BehaviorSubject

private $models: BehaviorSubject<Model[]> = new BehaviorSubject([]);
get models(): Model[] { return this.$models.getValue(); }
public addEmptyListItem(): void { 
let models = this.models();
models.push(new Model());
this.$models.next(models);
}

其中包含Model列表

export class Model { public foo: string; }

现在,如果我将[(ngModel)]="model.foo" name="foo"[value]="model.foo" (input)="model.foo = $event.target.value"交换:

<div *ngFor="let model of models">
<input [value]="model.foo" (input)="model.foo = $event.target.value">
{{model | json}}
</div>
<button (click)="addEmptyListItem()">add</button>

视图将正确更新。

问题

我忽略了为什么[(ngModel)]不起作用?

[(ngModel)]不应该也生成类似于上面提到的东西吗(参见 Angular 2 中的双向数据绑定)?

name属性在循环中必须是唯一的*ngFor您可以使用index进行。

更改您的代码,例如:

<div *ngFor="let model of models;let i = index"">
<input [(ngModel)]="model.foo" name="foo{{i}}">
</div>

最新更新