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

标签 angular directive

我的模板:

<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/

相关文章:

angular - 在加载完成之前从 HTML 中获取一个参数

angular - 动态渲染 Kendo Column

javascript - Angular 4 - 选择用于枚举不起作用的选择

javascript - AngularJS UI 路由器 : ui-sref and directive

jquery-ui-sortable - 将参数从指令传递给回调

javascript - 单击指令 ng-repeat 项时如何切换 ng-class

javascript - Angular 2 - 如何显示多选下拉列表的选定选项?

javascript - 恢复到旧版本的 Ionic 2 CLI

c++ - 匿名 namespace 内部/外部的 Typedef?