11

I am trying to achieve this functionality but getting error

<div *ngFor="let item of items; index as i">
    <div #menu{{i}}>
        //Some code
    </div>
    <div (onClick)="Clicked($event,menu{{i}})">
        //Some other code
    </div>

Got interpolation ({{}}) where expression was expected at column 19 in [Clicked($event,menu{{i}})]

Anyone knows how to fix it?

2
  • Tried (onClick)="Clicked($event,menu+i) and (onClick)="Clicked($event,'menu'+i) still no luck Commented Jul 30, 2018 at 13:38
  • @KeshanNageswaran tried this didn't work Commented Jul 30, 2018 at 14:19

3 Answers 3

12

You can use the ViewChildren decorator which returns a QueryList : you don't need to use an index anymore, Angular will handle all of that for you.

See this stackblitz to see it in action (open your console before clicking on the buttons)

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

1 Comment

Awesome! Thanks!
0

I just had this same problem and solved it by referencing the unique id of the same element that I had the template reference variable on, and I believe you could do the same.

<div class="outer-element" #outerElement>
  <div *ngFor="let item of items; index as i">
    <div id="menu{{i}}">
        //Some code
    </div>
    <div (onClick)="Clicked($event, outerElement.querySelector('#menu' + i)">
        //Some other code
    </div>
  </div>
</div>

Comments

-2

Dynamic Template Reference is not feasible in Angular. You can try these 2 solutions.

Solution 1 :

Attach 'id' property to div element i.e 'menu1' and pass the id to the component on click method and access the DOM using document.querySelector()

Solution 2:

Create a attribute directive in which you can pass id as @Input and access elementRef in the constructor().

Comments

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.