我想通过ngModel
将ngFor
循环中的模型绑定到输入字段,但是如果我将另一个项目添加到我的列表中,模型的值将在模型中可见,但在视图中不可见。
<div *ngFor="let model of models">
<input [(ngModel)]="model.foo" name="foo">
{{model | json}}
</div>
<button (click)="addEmptyListItem()">add</button>
如果我在视图中输入bar
model | 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>