Victor Mukherjee
Victor Mukherjee

Reputation: 11045

Angular: Get reference of one directive instance on host from another directive

My template:

<div myDirective myOtherDirective>Hello World</div>

myDirective:

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

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

Upvotes: 9

Views: 3469

Answers (1)

yurzui
yurzui

Reputation: 214175

It should be available throught DI

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

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

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;
}

Upvotes: 17

Related Questions