最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass element with dynamic reference angular2? - Stack Overflow

programmeradmin0浏览0评论

I have elements inside ngFor loop. Each elements get reference like this #f{{floor}}b. As you see floor is a variable. I want to pass these elements to a function. Code:

<button #f{{floor}}b (click)="onClick(f{{floor}}b)"></button>

I tried this but it only pass a string like this f5b not the element itself:

<button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>

Full code:

<div *ngFor="let floor of floors">
  <button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>
</div>

floor is a number and floors is an array of numbers.

I have elements inside ngFor loop. Each elements get reference like this #f{{floor}}b. As you see floor is a variable. I want to pass these elements to a function. Code:

<button #f{{floor}}b (click)="onClick(f{{floor}}b)"></button>

I tried this but it only pass a string like this f5b not the element itself:

<button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>

Full code:

<div *ngFor="let floor of floors">
  <button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>
</div>

floor is a number and floors is an array of numbers.

Share Improve this question edited Nov 10, 2017 at 15:07 Mihai Alexandru-Ionut 48.4k13 gold badges105 silver badges132 bronze badges asked Nov 10, 2017 at 15:00 YamonaYamona 1,1301 gold badge20 silver badges37 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

It is okay to have same template variable name inside *ngFor, no need to make unique template variable name inside *ngFor.

Html

<div *ngFor="let floor of floors">
  <button #fb (click)="onClick(fb)"></button>
</div>

Even by having similar template name, you can query the DOM using @ViewChildren decorator.

@ViewChildren('fb') fbButtons:QueryList<any>;

Just use the same variable

<div *ngFor="let floor of floors">
  <button #btn (click)="onClick(btn)"></button>
</div>

or use $event.target/currentTarget

发布评论

评论列表(0)

  1. 暂无评论