简体   繁体   English

如何使用angular 6在函数中传递动态模板引用变量

[英]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}})]在 [Clicked($event,menu{{i}})] 的第 19 列处得到了插值 ({{}})

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.您可以使用返回QueryListViewChildren装饰器:您不再需要使用索引,Angular 将为您处理所有这些。

See this stackblitz to see it in action (open your console before clicking on the buttons)查看此stackblitz以查看它的实际效果(在单击按钮之前打开您的控制台)

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.我刚刚遇到了同样的问题,并通过引用我拥有模板引用变量的同一元素的唯一 id 解决了它,我相信你可以做同样的事情。

<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.动态模板引用在 Angular 中不可行。 You can try these 2 solutions.您可以尝试这两种解决方案。

Solution 1 :解决方案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()将 'id' 属性附加到 div 元素,即 'menu1' 并通过单击方法将 id 传递给组件并使用 document.querySelector() 访问 DOM

Solution 2:解决方案2:

Create a attribute directive in which you can pass id as @Input and access elementRef in the constructor().创建一个属性指令,您可以在其中将 id 作为 @Input 传递并在构造函数()中访问 elementRef。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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