Search code examples
angularevent-binding

Dynamic template variable inside event binding


I have an angular component with this kind of template variable name

#name_{{i}}

inside a *ngFor, so that any component generated has a different variable name. I need to pass the entire variable (not as a string, as a reference to the template variable) to a function in a button event binding inside the same *ngfor, like this

(click)="myFunction(name_{{i}})"

Now, I cannot pass it like this

(click)="myFunction('name_'+i)"

because myFunction doesn't want a string as variable, but the template variable reference.

Passing the interpolation inside the event binding causes me this error:

Parser Error: Got interpolation ({{}}) where expression was expected

How can I pass the template variable to the function without using interpolation, as the variable is dynamic?


Solution

  • You don't need to do so.

    You don't have to generate a name for each instance or even use @viewChildren.

    You can use the same reference name for each element generated by ngFor.

    In fact, the reference call is automatically attached to the reference variable it is generated with inside the *ngFor loop directive (it's like a scope inside the template passed to the ngFor directive)

    You can write it like this :

    <div #item *ngFor="let item of list" (click)="myFunction(item)"></div>
    

    Hope it helps :)