假设我有两个指令:
@Directive({
selector: '[appDirective1]'
})
export class Directive1Directive {
public alone = true;
constructor(private element: ElementRef<HTMLInputElement>) { }
ngOnInit() {
if (this.alone) {
this.element.nativeElement.innerHTML = "I am alone";
} else {
this.element.nativeElement.innerHTML = "I have a friend";
}
}
}
@Directive({
selector: '[appDirective2]'
})
export class Directive2Directive {
constructor() { }
}
如果 Directive2
出现在同一个元素上,我希望 Directive1
改变它的行为。例如,它们应该有不同的行为。
<div appDirective1></div>
<div appDirective1 appDirective2></div>
我是否可以在不添加促进通信的服务的情况下执行此操作*?
StackBlitz 示例:https://stackblitz.com/edit/angular-bgqd15
*我想避免为此创建新服务,因为这感觉有点矫枉过正。
最佳答案
您可以使用 Host() 通过构造函数注入(inject)相邻指令装饰器,并使其成为Optional()
constructor(@Optional() @Host() public friend: Directive2Directive) { }
ngOnInit() {
if (this.friend) {
this.element.nativeElement.innerHTML = "I have a friend";
} else {
this.element.nativeElement.innerHTML = "I am alone";
}
}
组件、指令和提供程序是可注入(inject)的,您可以将 DI 限制为仅在当前 host 级别上搜索。
关于angular - 如何检查同一元素上是否存在另一个指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312669/