Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass element with dynamic reference angular2?

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.

like image 696
Yamona Avatar asked Nov 10 '17 15:11

Yamona


2 Answers

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>;
like image 148
Pankaj Parkar Avatar answered Sep 25 '22 00:09

Pankaj Parkar


Just use the same variable

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

or use $event.target/currentTarget

like image 37
yurzui Avatar answered Sep 24 '22 00:09

yurzui