首页 > 解决方案 > Angular6 在指令本身中获取所有具有相同指令名称的元素

问题描述

我有一个名为 isSelected 的指令,我将它应用于不同组件中的几个元素,例如

<i isSelected class="icon"></i>
<i isSelected class="icon"></i>
<i isSelected class="icon"></i>
<i isSelected class="icon"></i>

不,我怎样才能在指令本身中使用“isSelected”指令来获取元素。

@Directive({
 selector: '[isSelected]'
})
export class IsSelectedDirective {
   //I need to get all the elements using my directive
}

StackBlitz 代码

在 StackBlitz Code onHover over h1 tag 中,hovered tag 应该有 1 opacity 其余 h1 tags opacity 应该上升到 0.5。

如果您需要任何其他信息,请发表评论。

标签: angulartypescriptangular6angular-directive

解决方案


在指令的构造函数中,您可以编写类似

constructor(private el: ElementRef, private myService: MyService) {
    myService.push(el); 
}

无论哪个元素应用此指令,都会调用它的构造函数。创建一个服务,该服务维护所有这些元素的数组,并使用每个调用的构造函数将元素推送给它。这条线上的东西

@Inject()


export class MyService{
 private elementArray: Array<ElementRef> = [];

 public push(el: ElementRef) {
    this.elementArray.push(el):
 }
 public getElements() {
 return this.elementArray;
 }
}

然后在指令中,您可以使用相同的服务来获取所有这些元素的列表。


推荐阅读