3

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?

2
  • can you post the entire element? What is name_? Did you try (click)="myFunction({{ 'name_' + i }})" Commented Jan 10, 2020 at 10:58
  • what bothers the compiler is my use of interpolation {{}} inside the function call of the event binding; as far as I know in fact it shouldn't be done. I was looking for alternative ways Commented Jan 10, 2020 at 11:03

2 Answers 2

5

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

You can make use of @ViewChildren

//Html
<element *ngFor="let each of all" (click)="myFunction(i)" #myElement></element>

//TS
 @ViewChildren('myElement') myElementList: QueryList<YourType>;

 myFunction(ind) {
  console.log(this.myElementList.toArray()[ind]);
 }

1 Comment

thank you, unfortunately this solution isn't working for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.