I want to create a custom event which can trigger from any component and get listened to any component within my angular 7 app
Suppose I have 1 component in which I have a button on click on which I want to trigger my custom event with some data. Next, there will be another component which will constantly listening for that event when it triggers it will execute some code and update the ui accordingly.
How should I implement it?
Well, well, well, what you're looking for is a Shared Service. This shared service will have a BehaviorSubject
that will act as a source for the data. Through this, you will be able to push new data streams. And then you will expose this BehaviorSubject
asObservable
.
You will then subscribe
to this Observable
from all the components where you want to listen for data changes and then react accordingly.
This is what this is going to look like in code:
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
@Injectable()
export class SharedService {
private data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
data$: Observable<any> = this.data.asObservable();
constructor() { }
setData(newData) {
this.data.next(newData);
}
}
You can now inject the SharedService
in any controller you want and call setData
from the component that you want to push new data from(see the AppComponent
from the Sample StackBlitz for more details). And then you'll also be injecting the SharedService
in other components and in there, you'll subscribe
to data$
in their ngOnInit
(see the HelloComponent
from the Sample StackBlitz for details)
Here's a Sample StackBlitz for your ref.