Consider this Angular 6 component
@Component({
template: '<div my-directive>content</div>'
})
export class ACustomComponent {}
What is the simplest way for me to inject the specific instance of the component inside the directive's constructor?
@Directive()
export class MyDirective {
// how to reference the component whose template hosts this directive?
constructor(private hostComponent: Component) {}
}
The simplest way I've thought to do this is to use a service provided in @Component()
, store the component instance in a service property, then inject that same service in the directive and retrieve the instance from that property. Wondering if there is a simpler, more generic way (so I don't have to provide that service every time I need to do this) that means the directive doesn't need to know the type of its host component.
PS: My question is different from this one because whereas the other wants the component instance that the directive is directly applied to -- <my-cmp my-directive></my-cmp>
, I'm asking for the nearest parent component whether the directive is applied to it directly or to a native HTML element within its template.
Basically, the problem I want to solve is: I need to execute methods within the directive and bind them to the this
context of the component that hosts them without the directive knowing the component's type ahead of time.
someMethod.bind(this.hostComponent)();