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

时间:2019-07-29 05:35:21

标签: angular directive

我的模板:

<div myDirective myOtherDirective>Hello World</div>

myDirective:

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

如何从myOtherDirective内部获得对MyDirective的引用?

1 个答案:

答案 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;
}
相关问题