Angular6在指令本身中获取具有相同指令名称的所有元素

问题描述 投票:0回答:2

我有一个名为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 code

在StackBlitz Code onHover over h1标签上,hovered标签应该有1个不透明度,其余的h1标签不透明度应该上升到0.5。

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

angular typescript angular6 angular-directive
2个回答
1
投票

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

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;
 }
}

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


0
投票

经过深思熟虑,我发现了这种方法。

@Directive({
 selector: '[isSelected]'
})
export class IsSelectedDirective {
  allElements;

  ngOnInit() {
    this.renderer.addClass(this.elem.nativeElement, 'isSelected')
  }

  ngAfterViewInit() {
    this.allElements = this.document.querySelectorAll('.isSelected');
  }
}

方法是在初始化指令时添加类,稍后在初始化视图时查询添加了类的元素。它对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.