简体   繁体   English

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

[英]Angular6 get all the elements having same Directive name in the Directive itself

I have a Directive named isSelected and I apply it on few elements in different components like 我有一个名为isSelected的指令,并将其应用于不同组件中的一些元素,例如

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

No how can I get the elements using 'isSelected' Directive in the Directive itself. 我无法在指令本身中使用“ isSelected”指令获取元素。

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

StackBlitz code StackBlitz代码

In the StackBlitz Code onHover over h1 tag, hovered tag should have 1 opacity rest h1 tags opacity should rise to 0.5. 在StackBlitz Code onHover over h1标签上,悬停的标签应具有1个不透明度,其余的h1标签的不透明度应提高到0.5。

Please comment if you need any additional information. 如果您需要任何其他信息,请发表评论。

Inside the constructor of your directive you can write something like 在指令的构造函数中,您可以编写类似

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

Whichever element applies this directive, it's constructor will be called. 无论使用此指令的哪个元素,都将调用其构造函数。 Create a service which maintains the array of all these elements and with every constructor called push the element to it. 创建一个服务来维护所有这些元素的数组,并通过调用每个构造函数的方法将元素推送到其中。 Something on this line 这条线上的东西

@Inject()


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

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

Then inside the directive you can use the same service to get the list of all those elements. 然后,在指令内部,您可以使用相同的服务来获取所有这些元素的列表。

I found this approach after giving it a lot of thought. 经过深思熟虑,我发现了这种方法。

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

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

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

The approach is Adding a class while the directive is initialized and later when the view is initialized querying the elements with the class added. 该方法是在初始化指令时添加一个类,然后在初始化视图时查询添加了类的元素。 It worked for me. 它为我工作。

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

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