首页 > 解决方案 > 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?

标签: angular

解决方案


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/


推荐阅读