简体   繁体   中英

How to pass a dynamic template reference variable in a function using angular 6

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?

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)

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>

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

Solution 1 :

Attach 'id' property to div element ie '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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM