angularangular-directive

How to access host component from directive?


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.


Solution

  • You can just inject it

    class MyDirective {
      constructor(private host:MyComponent) {}
    

    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.