[英]How to pass element with dynamic reference angular2?
I have elements inside ngFor
loop. 我在ngFor
循环中有元素。 Each elements get reference like this #f{{floor}}b
. 每个元素都像#f{{floor}}b
一样被引用。 As you see floor
is a variable. 如你所见, floor
是一个变量。 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: 我试过这个,但它只传递像这个f5b
的字符串f5b
不是元素本身:
<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. floor
是一个数字, floors
是一组数字。
It is okay to have same template variable name inside *ngFor
, no need to make unique template variable name inside *ngFor
. 它是好的,有内同一个模板变量名*ngFor
,没有必要作出独特的模板变量名中*ngFor
。
Html 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
装饰器查询DOM。
@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
或使用$event.target/currentTarget
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.