Check out our Angular Book Series.

How do I listen for an Angular Event in TypeScript?

I'm building a custom Angular service for a client project that will create modal and other popups. If certain interaction occurs within the modal, then the modal should dispatch an event and the service needs to close the modal. In Angular you can use an EventEmitter to dispatch the event from the component's class. Create the emitter as a property on the component's class and add the @output metadata:


@Output()
myEvent : EventEmitter<any> = new EventEmitter();

Then to dispatch the event use the emit method:


this.myEvent.emit('Emitted Value');

That does exactly what I need in the component side. However, to listen for the event, most of the documentation I can find talks about doing so in the HTML template:


<MyComp
(myEvent)="onMyEvent($event)">

</MyComp>

Unfortunately, the service cannot add that event handler onto HTML because there is no HTML, so that was a no go for my use case. How do you do it?

After the service creates the component and displays it, it has an instance to that component class. We can introspect into the component class to get access to the emitter, and subscribe to it:


myCompRef.instance.myEvent.subscribe((value) =>
{
// do something
});

Under the hood the EventEmitter is a Subject, which is like an Observable.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.