如何使用动态参考angular2传递元素? [英] How to pass element with dynamic reference angular2?
问题描述
我在 ngFor
循环中有元素。每个元素都可以像 #f {{floor}} b
那样引用。如您所见 floor
是一个变量。
我想将这些元素传递给函数。
代码:
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>
我试过这个,但它只传递一个这样的字符串 f5b
不是元素本身:
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>
完整代码:
<div *ngFor="let floor of floors">
<button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>
</div>
floor
是一个数字和 floors
是一组数字。
floor
is a number and floors
is an array of numbers.
推荐答案
在 * ngFor
中可以使用相同的模板变量名称,无需在 * ngFor
中创建唯一的模板变量名称。
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>
即使拥有类似的模板名称,也可以使用 @ViewChildren查询DOM
decorator。
Even by having similar template name, you can query the DOM using @ViewChildren
decorator.
@ViewChildren('fb') fbButtons:QueryList<any>;
这篇关于如何使用动态参考angular2传递元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!