Broadcasting Events In Angular

In this article, we will learn about Broadcasting events in Angular applications. Broadcasting events is generally used to broadcast messages or data to the whole application.

Prerequisites

  • Basic knowledge of Angular
  • Visual Studio Code
  • Node and NPM installed
  • Bootstrap

For this article, I have created an Angular project using Angular 12. For creating an Angular project, we need to follow the following steps:

In Angular, you can broadcast events from a parent component to its child components using the @Output decorator and the EventEmitter class. Here's how it works:

  1. Define an output property in the parent component: Use the @Output decorator to define an output property in the parent component. The decorator is used to specify that this property is an output property that can be used to emit events.
    import { Output, EventEmitter } from '@angular/core';
    
    export class ParentComponent {
      @Output() messageEvent = new EventEmitter<string>();
    }
    
  2. Emit events from the parent component: Use the emit method of the EventEmitter class to emit events from the parent component. You can emit an event whenever you want to broadcast a message to its child components.
    export class ParentComponent {
      ...
      sendMessage() {
        this.messageEvent.emit('Hello from the parent!');
      }
    }
    
  3. Listen to events in the child component: In the child component, you can use the (messageEvent) event binding to listen to events emitted by the parent component. The event binding is used to bind the output property of the parent component to a method in the child component that will be called whenever an event is emitted.
    import { Component, Input } from '@angular/core';
    
    export class ChildComponent {
      @Input() message: string;
    
      receiveMessage($event) {
        this.message = $event;
      }
    }
    
    <app-child [message]="message" (messageEvent)="receiveMessage($event)"></app-child>
    

With these steps, you can broadcast events from a parent component to its child components in Angular.

In Angular, events can be broadcast from a component to its descendants using the EventEmitter class. However, if there are no parent-child components, you can still make use of Angular's event system by using services to communicate between components.

Here's an example of how you could use a service to communicate events between components:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EventService {
  private eventSubject = new Subject<any>();

  emitEvent(event: any) {
    this.eventSubject.next(event);
  }

  getEvent() {
    return this.eventSubject.asObservable();
  }
}

In this example, we have created a EventService that allows you to emit events using the emitEvent method and subscribe to events using the getEvent method. You can use this service in any component in your application to broadcast events and receive them.

Here's an example of how you could use the service in a component:

import { Component, OnInit } from '@angular/core';
import { EventService } from './event.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-example-component',
  template: `
    <button (click)="emitEvent()">Emit Event</button>
  `
})
export class ExampleComponent implements OnInit {
  private eventSubscription: Subscription;

  constructor(private eventService: EventService) { }

  ngOnInit() {
    this.eventSubscription = this.eventService.getEvent().subscribe(event => {
      console.log('Received event:', event);
    });
  }

  emitEvent() {
    this.eventService.emitEvent({ message: 'Hello from Example Component!' });
  }

  ngOnDestroy() {
    this.eventSubscription.unsubscribe();
  }
}

In this example, the ExampleComponent subscribes to events using the EventService in the ngOnInit lifecycle hook and emits an event when the button is clicked. This allows you to broadcast events between components even if they are not related through a parent-child relationship.