9

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?

1 Answer 1

17

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

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?
It's common pattern that Angular uses itself internally
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.
Works like a charm! Thank you! However, could you please point me out any documentation related to this behaviour?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.