需要查找* ngFor生成的输入字段的值

时间:2018-12-19 12:47:33

标签: angular

app.component.html:

<div *ngFor="let ivalue of arraytoDispaly;let i = index;">
    <input type="text" [value]="ivalue.inputValue" />
    <button (click)='GetId(i)'>GetID</button>

app.component.ts:

arraytoDispaly = [
{'inputValue':'abc'},
{'inputValue':'def'},
{'inputValue':'ghi'}];
GetId(val){
    console.log()
   }

需要在单击按钮时获取输入字段的值,我使用了ElementRef和@ViewChild,但未获取该值。任何人都可以指导我该怎么做,尽管我正在使用document.getElementById通过id来获取价值,但需要了解访问值的Angular方式,谢谢

3 个答案:

答案 0 :(得分:2)

您可以像下面这样在ngFor中传递当前值而不是索引-

<div *ngFor="let ivalue of arraytoDispaly;let i = index;">
    ....
<button (click)='GetId(ivalue)'>GetID</button>

GetId(val){
  console.log(val.inputValue)
}

答案 1 :(得分:0)

尝试:

<div *ngFor="let ivalue of arraytoDispaly;let i = index;">
    <input #i type="text" [value]="ivalue.inputValue" />
    <button (click)='getId(i.value)'>GetID</button>
</div>

getId(val){
    console.log(val)
   }

Working Stackblitz


PS:方法应采用驼峰式(getId而非GetId

答案 2 :(得分:0)

我们可以使用 ngModel 在对象和输入元素之间同步数据

<div *ngFor="let elm of arraytoDispaly;">
    <input type="text" [(ngModel)]="elm.inputValue" /> {{elm.inputValue}}
</div>
相关问题