Say I have the following markup:
<my-comp myDirective></my-comp>
Is there any way I can access the component instance from the directive?
More specifically I want to be able to access the properties and methods of MyComponent
from MyDirective
, ideally without adding anything to the HTML above.
You can just inject it
A severe limitation is, that you need to know the type of the component in advance.
See also https://github.com/angular/angular/issues/8277
It also provides some workarounds for when you don't know the type in advance.
If you want to use the attribute directive on your custom components you could have those components extend from an abstract class and 'forwardRef' the abstract class type to your component type. This way you can make angular's DI select on the abstract class (within your directive).
Abstract class:
Custom Component:
Directive:
This way you can use the directive on any component that extends your abstract class.
This will of course only work on your own components.
Your directive could be the generic one that can be applied to any of your components. So, in that case, injecting the component in constructor would not be possible, So here is one other way to do the same
Inject the
ViewContainerRef
in constructorand then get it using
This is taken from the github issue and works like a charm. The downside is needing to know the components beforehand, but in your case you would need to know the methods you're using anyway.
Credit: https://github.com/angular/angular/issues/8277#issuecomment-323678013