Blog>
Snippets

Communicating Between Angular Elements

Outline methods for inter-element communication such as shared services or direct DOM events when using multiple Angular Elements on a page.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

// Shared service for communication
@Injectable({ providedIn: 'root' })
export class SharedService {
    private messageSource = new BehaviorSubject<string>('initial message');
    currentMessage = this.messageSource.asObservable();

    changeMessage(message: string) {
        this.messageSource.next(message);
    }
}
This code represents a shared service with a BehaviorSubject to allow elements to subscribe and receive updates when the message changes.
import { Component, OnDestroy } from '@angular/core';
import { SharedService } from './shared.service';
import { Subscription } from 'rxjs';

// First Angular Element Component
@Component({
    selector: 'app-sender',
    template: `<input type="text" (input)="sendMessage($event.target.value)">`
})
export class SenderComponent {
    constructor(private sharedService: SharedService) {}

    sendMessage(message: string) {
        this.sharedService.changeMessage(message);
    }
}
This code represents an Angular element that sends messages. It includes an input field where the user can type a message, which is then sent to the shared service on input events.
import { Component, OnInit, OnDestroy } from '@angular/core';
import { SharedService } from './shared.service';
import { Subscription } from 'rxjs';

// Second Angular Element Component
@Component({
    selector: 'app-receiver',
    template: `<div>Message: {{message}}</div>`
})
export class ReceiverComponent implements OnInit, OnDestroy {
    message: string;
    private subscription: Subscription;

    constructor(private sharedService: SharedService) {}

    ngOnInit() {
        this.subscription = this.sharedService.currentMessage.subscribe(message => {
            this.message = message;
        });
    }

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
This code illustrates an Angular element that receives messages. It subscribes to the shared service to listen for changes in the message and will automatically update its view when the message changes.
// Listening to a Custom Event
window.addEventListener('myCustomEvent', (event) => {
    console.log('Custom event data:', event.detail);
});

// Dispatching a Custom Event from an Angular Element
@Component({
    //... component metadata
})
export class MyCustomElement {
    sendDataToOtherElements(data: any) {
        const event = new CustomEvent('myCustomEvent', { detail: data });
        window.dispatchEvent(event);
    }
}
This code depicts how to use custom DOM events to communicate between Angular elements. An event listener is added to listen for 'myCustomEvent', and a method is provided in an Angular element to dispatch this event with additional data.