ZhouQing
ZhouQing

Reputation: 23

How can I get the instance of host component for directive?

Before ng9, I can get the instance by:

Inject the ViewContainerRef in constructor

constructor(private _viewContainerRef: ViewContainerRef) { }

and then get it using

let hostComponent = this._viewContainerRef["_data"].componentView.component;

But in ng9, there is no _data property in ViewContainerRef:

How can I do in ng9? Thanks!

Upvotes: 0

Views: 808

Answers (1)

Eliseo
Eliseo

Reputation: 57981

If your directive is applied to a unique kind of component, you can use in constructor

constructor(@Optional() @Host() private component:YourComponent){}

NOTE: You need "wait" to ngAfterViewInit to get the value of a variable in the component

Upvotes: 2

Related Questions