I have 3 components in Angular-9 Application as shown below:
Component 1
<div>
// I have a button here with Click Event.
</div>
Component 2
<div>
// I have a Grid here.
</div>
In a class file I'm getting Data and Binding Grid using ngOnInit() method.
And I'm using both Components in third component as below:
Component 3
<div id='third-component'>
<component-one></component-one>
<component-two></component-two>
</div>
I want to refresh the Component2 data on click of a button that is there in Component1. How to do this?
You can use rxjs BehaviorSubject.
First just creat a service called data.service.ts and in that create an observable of type BehaviorSubject and a function to push the value into that BehaviorSubject.
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
public notify = new BehaviorSubject<any>('');
notifyObservable$ = this.notify.asObservable();
public notifyOther(data: any) {
if (data) {
this.notify.next(data);
}
}
and in component1.ts inject that service and on button click just send {refresh: true} object in notifyOther function which will be subscribed by component2 later.
refreshGridInAnotherComponent(){
this.dataService.notifyOther({refresh: true});
}
and in your component2.ts you can subscribe from that observable on component's ngOnInit like this
copmonet2.ts
ngOnInit(){
this.dataService.notifyObservable$.subscribe(res => {
if(res.refresh){
// get your grid data again. Grid will refresh automatically
this.dataService.getData();
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With