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

1

8

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?

Lumpfish answered 29/7, 2019 at 5:35 Comment(0)
N
16

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;
}
Nerveracking answered 29/7, 2019 at 5:38 Comment(4)
I was kind of sceptical about constructor injection, since it might mess with the order of instantiation of the directives, or, a circular dependency if both the directives need to refer each other?Lumpfish
It's common pattern that Angular uses itself internallyNerveracking
Just a critique on the wording of this question - Does this work? "It should" isn't very confidence building. I'll try this - but It would be nice to know for sure if this is the right way.Haplography
Works like a charm! Thank you! However, could you please point me out any documentation related to this behaviour?Repressive

© 2022 - 2024 — McMap. All rights reserved.