我的模板:
<div myDirective myOtherDirective>Hello World</div>
myDirective:
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
private readonly otherDirective: MyOtherDirective; // How to instantiate this?
}
如何从myOtherDirective
内部获得对MyDirective
的引用?
答案 0 :(得分:4)
应该可以通过DI来使用
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
constructor(private otherDirective: MyOtherDirective) {}
}
在同一元素上没有这样的指令,然后确保使用@Optional
装饰器。
或者,您也可以将其作为@Input
my-other.directive.ts
@Directive({
selector: '[myOtherDirective]',
exportAs: 'myOtherDirective'
})
export class MyOtherDirective {}
template.html
<div myDirective [otherDirective]="other" #other="myOtherDirective"
myOtherDirective>Hello World</div>
my.directive.ts
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input() otherDirective: MyOtherDirective;
}