我为我的指令有两个选择器dirA
和dirNotA
。该指令应根据使用的选择器继续进行。有什么方法可以确定在指令中使用了哪个选择器?
我既不希望有多个指令,也不希望带有参数的指令。我希望有一个带有多个选择器的指令,并根据模板中使用的选择器确定操作过程。
这样的东西
@Directive({
selector: '[dirA], [dirNotA]`
})
class DirectiveA implement OnInit {
ngOnInit() {
// here we detected which selector was used
if (dirASelector) {
...
}
}
}
任何想法如何在指令本身中获取此信息?
您可以使用继承。
class DirectiveAOrNotA implements OnInit {
// common logic here
}
@Directive({
selector: '[dirA]`
})
export class DirectiveA extends DirectiveAOrNotA {
// differences here
}
@Directive({
selector: '[dirNotA]`
})
export class DirectiveNotA extends DirectiveAOrNotA {
// differences here
}
您可以使用ElementRef
并检查其属性中的选择器。
指令
import { Directive, OnInit, ElementRef } from '@angular/core';
@Directive({
selector: '[dirA], [dirNotA]'
})
class DirectiveA implement OnInit {
constructor(private _elRef: ElementRef) { }
ngOnInit() {
if ((this._elRef.nativeElement.attributes).hasOwnProperty('dirA')) {
// selector is 'dirA'
} else if ((this._elRef.nativeElement.attributes).hasOwnProperty('dirNotA')) {
// selector is 'dirNotA'
}
}
}
工作示例:Stackblitz