Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

typescript - How to set unique template reference variables inside an *ngFor? (Angular)

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>

(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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...