Update the dom of a component from a service

1. Create a Service with an EventEmitter or Subject

You’ll use a Subject here because it’s more versatile than EventEmitter, which is generally used for @Output in components.

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

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

// Observable stream that components can subscribe to
public updateObservable = this.updateSubject.asObservable();

constructor() { }

public requestDomUpdate(data: any) {
this.updateSubject.next(data);
}
}

2. Inject and Subscribe to the Service in Your Component

In your component, inject the service and subscribe to the observable to receive updates.

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { DomService } from './dom.service';

@Component({
selector: 'app-my-component',
template: `<div *ngIf="displayData">{{ displayData }}</div>`
})
export class MyComponent implements OnDestroy {
displayData: any;
private updatesSubscription: Subscription;

constructor(private domService: DomService) {
this.updatesSubscription = this.domService.updateObservable.subscribe({
next: (data) => {
this.displayData = data;
// Additional actions to update DOM
}
});
}

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

3. Trigger Updates from the Service

Whenever you need to update the component’s view from somewhere in your app, call the requestDomUpdate method on your service with the necessary data.

// Somewhere in your application
this.domService.requestDomUpdate("New Data to Display");
Scroll to Top