justin.m.chase
justin.m.chase

Reputation: 13685

How can I get a component instance from within an event handler in Angular?

I have a dynamic component that I need to get a reference to in the event handler function. I can't use ViewChild because these components are dynamic and inside templates, etc.

<example #e (click)="onExample(e)" />

When I do the above e is undefined. How can I get the reference to the component itself (not the element) from within the handler?

Upvotes: 1

Views: 1057

Answers (1)

Dani P.
Dani P.

Reputation: 1138

For projected content you can use ContentChild instead of ViewChild, maybe that fits your case - see docs: https://angular.io/api/core/ContentChild.

This is a good article on the topic: https://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/

Upvotes: 1

Related Questions