Angular:从另一个指令获取主机上一个指令实例的引用 [英] Angular: Get reference of one directive instance on host from another directive

查看:175
本文介绍了Angular:从另一个指令获取主机上一个指令实例的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板:

<div myDirective myOtherDirective>Hello World</div>

myDirective:

myDirective:

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

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

How can I get a reference to myOtherDirective from inside MyDirective?

推荐答案

应该可以在DI中使用

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

在同一元素上没有这样的指令,然后确保使用 @Optional 装饰器.

It there's no such directive on the same element then make sure you use @Optional decorator.

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

Alternatively, you can pass it as an @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;
}

这篇关于Angular:从另一个指令获取主机上一个指令实例的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆