Angular:从另一个指令获取主机上一个指令实例的引用

Vic*_*jee 3 directive angular

我的模板:

<div myDirective myOtherDirective>Hello World</div>
Run Code Online (Sandbox Code Playgroud)

我的指令:

@Directive({
    selector: '[myDirective]',
})
export class MyDirective {
  private readonly otherDirective: MyOtherDirective; // How to instantiate this?
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能myOtherDirective从内部获得参考MyDirective

yur*_*zui 7

它应该可以通过 DI 获得

@Directive({
    selector: '[myDirective]',
})
export class MyDirective {
  constructor(private otherDirective: MyOtherDirective) {}
}
Run Code Online (Sandbox Code Playgroud)

如果同一个元素上没有这样的指令,那么请确保使用@Optional装饰器。

或者,您可以将其作为 @Input

我的other.directive.ts

@Directive({
    selector: '[myOtherDirective]',
    exportAs: 'myOtherDirective'
})
export class MyOtherDirective {}
Run Code Online (Sandbox Code Playgroud)

模板.html

<div myDirective [otherDirective]="other" #other="myOtherDirective" 
      myOtherDirective>Hello World</div>
Run Code Online (Sandbox Code Playgroud)

my.directive.ts

@Directive({
   selector: '[myDirective]',
})
export class MyDirective {
   @Input() otherDirective: MyOtherDirective;
}
Run Code Online (Sandbox Code Playgroud)