2

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?

1
  • You can use rxjs Observable on service. Commented Oct 23, 2020 at 10:34

2 Answers 2

8

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();
          }
    })
}
Sign up to request clarification or add additional context in comments.

Comments

4

The answer to share data between angular components is: use an angular service

you can make the button from component1 trigger a function on the service

assuming that the data from component 2's grid also comes from the same service, once the data changes, the component refreshes automatically

this answer has a good example for you: https://stackoverflow.com/a/61806447/4604645

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.