Angular6 获取指令本身中具有相同指令名称的所有元素
Angular6 get all the elements having same Directive name in the Directive itself
我有一个名为 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 代码中,悬停在 h1 标签上时,悬停标签的不透明度应为 1,其余 h1 标签的不透明度应升至 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;
}
}
然后在指令中,您可以使用相同的服务来获取所有这些元素的列表。
经过深思熟虑,我找到了这个方法。
@Directive({
selector: '[isSelected]'
})
export class IsSelectedDirective {
allElements;
ngOnInit() {
this.renderer.addClass(this.elem.nativeElement, 'isSelected')
}
ngAfterViewInit() {
this.allElements = this.document.querySelectorAll('.isSelected');
}
}
方法是在初始化指令时添加 class,稍后在初始化视图时查询添加了 class 的元素。它对我有用。
我有一个名为 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 代码中,悬停在 h1 标签上时,悬停标签的不透明度应为 1,其余 h1 标签的不透明度应升至 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;
}
}
然后在指令中,您可以使用相同的服务来获取所有这些元素的列表。
经过深思熟虑,我找到了这个方法。
@Directive({
selector: '[isSelected]'
})
export class IsSelectedDirective {
allElements;
ngOnInit() {
this.renderer.addClass(this.elem.nativeElement, 'isSelected')
}
ngAfterViewInit() {
this.allElements = this.document.querySelectorAll('.isSelected');
}
}
方法是在初始化指令时添加 class,稍后在初始化视图时查询添加了 class 的元素。它对我有用。