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?

Nic3500
  • 8,144
  • 10
  • 29
  • 40
Danish
  • 325
  • 1
  • 4
  • 12

3 Answers3

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)

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>
Jack Connor
  • 111
  • 3
-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().

Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27