angular - 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 Code onHover over h1 tag 中,hovered tag 应该有 1 opacity 其余 h1 tags opacity 应该上升到 0.5。
如果您需要任何其他信息,请发表评论。
解决方案
在指令的构造函数中,您可以编写类似
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;
}
}
然后在指令中,您可以使用相同的服务来获取所有这些元素的列表。
推荐阅读
- azure - 如何使用 Azure B2C 处理多个 API
- php - 为什么我在没有 CSRF 令牌的情况下对 Laravel 的 HTTP 发布收到 301 响应?
- node.js - 在其他函数中调用回滚事务 - Node+KnexJS
- java - Spring转换器不转换自定义实体
- java - 是否可以从键列表初始化 HashMap 的键和值,将值设置为 0
- java - 为什么 FindById 返回 Optional?
- xcode - 从 React Native 更新 React Navigation 时出错
- python - 如何创建 spacy 的快捷链接?
- coldfusion - 将查询的查询进一步拆分为多个部分
- android - VS Xamarin.Forms (Android):使用 Xam.Plugin.Media 拒绝相机和存储访问