我的模板:
<div myDirective myOtherDirective>Hello World</div>
我的指令:
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
private readonly otherDirective: MyOtherDirective; // How to instantiate this?
}
我如何获得对
myOtherDirective
的引用从内部 MyDirective
?
最佳答案
它应该可以通过 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 {}
模板.html
<div myDirective [otherDirective]="other" #other="myOtherDirective"
myOtherDirective>Hello World</div>
my.directive.ts
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input() otherDirective: MyOtherDirective;
}
关于Angular:从另一个指令获取主机上一个指令实例的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57247686/