问题描述
我在*ngFor
循环中有一堆输入字段.该文档说模板引用变量应该是唯一的.有没有办法像#attendee-{{person.id}}
一样使它唯一?
I have a bunch of input fields in a *ngFor
loop. The documentation says that template reference variables should be unique. Is there a way to do something like #attendee-{{person.id}}
to make it unique?
<div *ngFor="let person of attendeesList">
<input #attendee [ngModel]="person.name" (blur)="changeName(attendee.value)"/>
</div>
(我知道可以选择(ngModelChange)="changeName($event)"
,但是出于某些原因,我需要使用 blur .具体地说,我不希望该模型进行更改,直到该人输入完姓名为止,并且我们已经确认该姓名不是空的且不是重复的姓名.
(I know that there is the option of doing (ngModelChange)="changeName($event)"
but there are reasons I need to use blur instead. Specifically, I don't want the model to change until the person is done typing the name and we have validated that the name is not empty and not a duplicate name.
推荐答案
您的模板引用变量已经是唯一的,因为您在嵌入式视图范围内使用了它:
Your template reference variable is already unique because you use it inside embedded view scope:
<div *ngFor="let person of attendeesList">
<input #attendee [ngModel]="person.name" (blur)="person.name = attendee.value"/>
</div>
Working Example
但是您甚至可以省略模板引用变量,如下所示:
But you can even omit template reference variable as shown below:
<div *ngFor="let person of attendeesList">
<input [ngModel]="person.name" (blur)="person.name = $event.target.value"/>
</div>
这篇关于如何在* ngFor中设置唯一的模板引用变量? (角度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!