How to access host component from directive?

AngularChef picture AngularChef · Sep 2, 2017 · Viewed 26.1k times · Source

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.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Sep 2, 2017

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.