Angular-如何使用单向绑定在ngFor循环中获取输入值 [英] Angular - How to get input value at ngFor loop with one way binding
问题描述
您能给我一种通过单向绑定在ngFor循环中获取输入值的方法吗?
Can you give me a way to get input value at ngFor loop with one way binding?
<div *ngFor="let d of dataList">
<input #inputValue type="text" [ngValue]="d.value">
<button *ngIf="!d.open" (click)="d.open = true">change</button>
<button *ngIf="d.open" (click)="save(d.id, NEWVALUE); d.open = false;">save</button>
<button *ngIf="d.open" (click)="d.open = false">cancel</button>
</div>`
如何设置NEWVALUE? 双向装订很容易. 但单击取消"后,值已更改 因为我不想要 因此可以避免这种情况.
How can I set NEWVALUE? with two-way binding is easy. but after click cancel, value already changed as I don't want. So would avoid that way.
我发现的一种解决方案是使用(ngModelChange).
One solution I've found is using (ngModelChange).
<div *ngFor="let d of dataList">
<input #inputValue type="text" [ngValue]="d.value" (ngModelChange)="dataChanged($event)">
<button *ngIf="!d.open" (click)="d.open = true">change</button>
<button *ngIf="d.open" (click)="save(d.id); d.open = false;">save</button>
<button *ngIf="d.open" (click)="d.open = false">cancel</button>
</div>
private newVal;
dataChanged(val) {
this.newVal = val;
}
save(id) {
saveDb(id, this.newVal);
}
我猜这不是清晰且经过优化的代码.
This is not clear and optimized code as I guess.
据我所知,使用#For进行模板绑定也不适用于ngFor.喜欢
As I know, template binding with # is also not work with ngFor. like
<div *ngFor="let d of dataList">
<input #inputValue_{{d.id}} type="text" [ngValue]="d.value">
<button *ngIf="d.open" (click)="save(inputValue_{{d.id}}.value); d.open = false;">save</button>
</div>
您对我有什么好的解决办法吗?
Do you have any good solution for me?
推荐答案
不可能直接提供模板变量,但是我为您做了替代选择
It is not posible you must provide the template variable directly, but I did an alternative for you
HTML
<div *ngFor="let item of array">
<input id="id_{{item.id}}" />
<button type="button" (click)="printValue('id_'+item.id)"> buton {{item.id}} </button>
</div>
组件
export class AppComponent {
array = [{id: 1}, {id: 2},{id: 3}]
printValue(value: any){
console.log(value);
var containputiner = document.querySelector("#"+value);
console.log(containputiner.value);
}
}
这篇关于Angular-如何使用单向绑定在ngFor循环中获取输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!