简体   繁体   English

如何从循环ngFor中的输入类型=“文本”中获取输入值

[英]How to get input value from input type=“text” in loop ngFor

I have problem about getting value from input type="text" in ngFor while I bind it with [(ngModel)] all of it has same value how can I bind all input in ngFor ? 我在与[(ngModel)]绑定时从ngFor的输入type =“ text”获取值时遇到问题,我所有的值都具有相同的值,如何绑定ngFor的所有输入?

html 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>

component 零件

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);
}

here is code plnkr.co 这是代码plnkr.co

If I understand this, you want to have the inputs bind to members of the listServiceFeature array. 如果我理解这一点,则希望将输入绑定到listServiceFeature数组的成员。 Is that right? 那正确吗? If that's what you want to do, you can bind directly to the array members using the index: 如果您要这样做,则可以使用索引直接绑定到数组成员:

  <input class="form-control" [(ngModel)]="listServiceFeature[i]" type="text" />

Now if you add some text to the added inputs and hit save you get the whole array on the console. 现在,如果您向添加的输入中添加一些文本,然后单击“保存”,则会在控制台上获得整个数组。

After a long search, if you are using a newer version of angular (Angular 4) you have to import FormModule 经过长时间的搜索,如果您使用的是更新版本的angular(Angular 4),则必须导入FormModule

Angular 4 - "Can't bind to 'ngModel' since it isn't a known property of 'input' " error Angular 4-“无法绑定到'ngModel',因为它不是'input'的已知属性”错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM