我有问题,从输入类型="文本"的值在ngFor,而我绑定它与[(ngModel)]所有它有相同的值,我怎么能绑定所有输入在ngFor ?
html<button (click)="saveFeature()" type="button">save</button>
<input class="form-control" type="text" />
<button (click)="addFeature()" type="button">Add</button>
<div *ngFor="let inputservice of servicesfeature_id; let i=index">
<input class="form-control" [(ngModel)]="listServiceFeature" type="text" />
<button (click)="RemoveFeature(i)" type="button">Remove</button>
</div>
组件
servicesfeature_id: any = [];
servicesfeature_length: number = 0;
listServiceFeature: any = [];
servicefeature_name: string;
saveFeature(): void {
console.log(this.listServiceFeature);
}
addFeature(): void {
this.servicesfeature_id.push('service' + this.servicesfeature_length);
this.servicesfeature_length += 1;
}
RemoveFeature(index): void {
this.servicesfeature_length -= 1;
this.servicesfeature_id.splice(index, 1);
}
这里是代码plnkr.co
如果我理解这一点,您希望将输入绑定到listServiceFeature
数组的成员。对吗?如果您想这样做,可以使用索引直接绑定到数组成员:
<input class="form-control" [(ngModel)]="listServiceFeature[i]" type="text" />
现在,如果您在添加的输入中添加一些文本并点击保存,您将在控制台上获得整个数组。
经过长时间的搜索,如果你使用的是新版本的angular (angular 4),你必须导入FormModule
Angular 4 - "Can't bind to 'ngModel'因为它不是'input'";误差