← Impulso Blog

Emitting global events with Angular

Making it possible for multiple components in different hierarchies to listen for an event

Blue Angular 2 card labeled “Emitindo Eventos Globais (Broadcast).”

Editorial translation by Impulso.

Angular card labeled “Emitindo Eventos Globais (Broadcast).”

Angular 2 introduced a different way of working with component properties and events. Anyone who developed with Angular 1.x is familiar with the broadcast() and emit() methods, which were called on the scope. That let us use $rootScope to fire global events that were accessible throughout the application, so any component interested in an event could listen for it using the on()method.

The new version introduces a new approach to property bindings and event bindings, now known as component inputs and outputs. These bindings are even easier to work with now.

But there’s a catch: with event binding, when a component fires an event through its Output, only its parent can listen for it. The event doesn’t propagate to the parent’s parent, or to the next parent up, and so on. Confused? Basically, with Angular’s traditional event binding, you can’t send out a broadcast that any component in the application can listen for, regardless of whether it’s the parent of the component that emitted it.

This week, I needed to emit an event from a small inner component that was nested inside at least two other components. I wanted the page (my main component) to listen for that event from all the way down there.

So I started looking into how events work in Angular and came up with a pretty simple solution: use a static service.

Using a service to register global events

One note: keep using Outputs to emit events between parent and child components. That’s the best way to do it. Only emit events through a service when you want to make them global.

Angular has an EventEmitter class that handles events within the framework. But if you look closely, EventEmitter is implemented on top of RxJs, which works with subscribers, among other things. So we can use subscribers with EventEmitter too. To do that, let’s implement a very simple service class:

import { EventEmitter } from '@angular/core';

export class EventEmitterService {

private static emitters: {
        [nomeEvento: string]: EventEmitter<any>
    } = {}

static get (nomeEvento:string): EventEmitter<any> {
        if (!this.emitters[nomeEvento])
            this.emitters[nomeEvento] = new EventEmitter<any>();
        return this.emitters[nomeEvento];
    }

Basically, we’re creating a class that imports EventEmitter from Angular core. If you look at the class, you’ll see we’re defining properties and methods that are static. That way, I don’t need a service instance in every class where I use it. We’ll just import the service into those classes and call its methods directly.

EventEmitterService.nomeDoMetodo();

So we’re defining a static property of type EventEmitter, but with a generic index signature, [nomeEvento: string]: EventEmitter, since we’ll be adding new events dynamically.

The static get() method exposes this property. If it already exists, we return it. Otherwise, we create it before returning it.

Once we have the EventEmitter object, we can use the emit() and subscribe() methods to work with events.

Emitting a global event

In the class that will fire the event, we’ll import our service and simply emit the event. It’s all pretty straightforward:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

import { EventEmitterService } from "../services/event-emitter.service";

@Component({
  selector: 'app-formulario',
  templateUrl: './formulario.component.html',
  styleUrls: ['./formulario.component.css']
})
export class FormularioComponent implements OnInit {

texto: string;

constructor() { }

ngOnInit() { }

botaoClick() {
    EventEmitterService.get('textChange').emit(this.texto);
  }

alertaClick() {
    EventEmitterService.get('showAlert').emit(this.texto);
  }

As you can see, we’ve defined two events, textChange and showAlert. These events are created dynamically by passing their names to the get()method.

Since get() returns an EventEmitter object, just call emit() to send whatever value you want with your event. I’m only passing strings in this example, but you could pass other primitive types or a more complex object:

EventEmitterService.get('testeObject').emit({
    nome: 'John Snow',
    email: 'snow.john@got.com'
});

Subscribing to (or listening for) global events

Now it’s time to register the classes that will listen for these events. The process is just as simple: import the service and specify which events you want to listen for in the class constructor:

import { Component } from '@angular/core';

import { EventEmitterService } from "./services/event-emitter.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

constructor() {
    EventEmitterService.get('textChange').subscribe(data => this.title = data);
    EventEmitterService.get('showAlert').subscribe(this.onAlertListener);
  }

The whole process is pretty easy. Here, we also call get() with the event name we want to access, but this time we’ll subscribe to listen for the event using the subscribe()method.

Notice that I did this two ways here: in one, I listen for the event and handle it inline with an arrow function, which receives the event data and assigns it to the local title property. In the other, I pass a function, onAlertListener, to the subscribe() method, and that function receives the event data and displays the alert.

Avoiding problems

Finally, to avoid performance issues in an Angular application that uses global events, I suggest that in every class where you listen for a global event, you call unsubscribe() for that event in your component’s OnDestroy method.

That way, you won’t leave anything behind in your application’s memory:

ngOnDestroy() {
    EventEmitterService.get('nomeDoEvrnto').unsubscribe();
}

However, there’s a small error in the unsubscribe() example I posted above.

This code will end up throwing an error. The correct way is to store the event subscription in a local property of the class that listens for the global event:

private sub: any = null;

Only then should you go into the ngOnDestroy() method and call unsubscribe():

ngOnDestroy() {
    if (this.sub) this.sub.unsubscribe();
}

Conclusion

Sometimes we’ll need to fire global events that a component far from the emitter can listen for, or that several components can listen for at once. We know this may not be good practice, but it depends a lot on each project’s requirements and specifics. If we do need to do it, though, Angular gives us a great way to do it, and better yet, it’s simple and straightforward.

Related articles