Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh one Component on click event of Another Component in Angular

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?

like image 324
Unknown Coder Avatar asked Jan 23 '26 06:01

Unknown Coder


1 Answers

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();
          }
    })
}
like image 94
Fahad Subzwari Avatar answered Jan 24 '26 22:01

Fahad Subzwari