Given following HTML template:
<input my-directive-a="foo" my-directive-b="bar"/>
Is there a way to detect within my-directive-a that on the same Host, my-directive-b is also present? Furthermore, how would I get access to that object?
Ideally, I would use some analogue to @ViewChild:
@Directive({
selector: '[my-directive-a]'
})
export class DirectiveA {
@ViewChild(DirectiveB) myDirectiveB: DirectiveB;
}
But this does only work in the host component.
I know that where are other answers that deal with the communication of two directives (e.g. through @Input or a shared service), but I don't want to force the users of my-directive-a to always declare my-directive-b as well. I already have a working solution for instantiating my-directive-b if not present, but since where are legitimate use cases for both directives to be declared independently of each other on the same host element, I wanted to optimize my solution to reuse my-directive-b instead of creating another instance of it.
Directives are injected into the component, which means that you will have absolutely no issue injecting them into each other.
See this demo
@Directive({
selector: '[appA]'
})
export class ADirective {
constructor(
private B: BDirective
) { }
ngAfterViewInit() {
console.log(this.B.some);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With