Angular 角度:从另一个指令获取主机上一个指令实例的引用
我的模板:Angular 角度:从另一个指令获取主机上一个指令实例的引用,angular,directive,Angular,Directive,我的模板: <div myDirective myOtherDirective>Hello World</div> 如何从MyDirective内部获取对myOtherDirective的引用?它应该可以通过DI获得 @Directive({ selector: '[myDirective]', }) export class MyDirective { constructor(private otherDirective: MyOtherDirective
<div myDirective myOtherDirective>Hello World</div>
如何从
MyDirective
内部获取对myOtherDirective
的引用?它应该可以通过DI获得
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
constructor(private otherDirective: MyOtherDirective) {}
}
如果在同一个元素上没有这样的指令,那么请确保使用@Optional
装饰器
或者,您可以将其作为@输入传递
my other.directive.ts
@Directive({
selector: '[myOtherDirective]',
exportAs: 'myOtherDirective'
})
export class MyOtherDirective {}
template.html
<div myDirective [otherDirective]="other" #other="myOtherDirective"
myOtherDirective>Hello World</div>
我对构造函数注入有点怀疑,因为它可能会扰乱指令实例化的顺序,或者,如果两个指令都需要相互引用,则会产生循环依赖?Angular内部使用它自己的常见模式只是对这个问题的措辞的一种批评-这行得通吗?“应该”不是很有信心。我会试试这个,但如果能确定这是不是正确的方法,那就太好了。
<div myDirective [otherDirective]="other" #other="myOtherDirective"
myOtherDirective>Hello World</div>
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input() otherDirective: MyOtherDirective;
}