How to trigger notification event in one component and listen in another component in Angular 4 (components do not have parent/child relation)

Viewed 6149

I want to make a change in one component after some activity in another component. The components do not have a parent/child relation. Please tell me the correct solution to this

2 Answers

you can create a shared service with bi-directional flow using private subjects and public observables. Both the components can subscribe to these observables, where one can push new values and other can react according to the new value changes.

Official docs!

Components in the plunker don't have any parent child relationship.

Working Plunker

 @Injectable()
export class MissionService {

  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();

  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();

  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }

  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}

Some other good ways to update a component according to other component changes:

  1. if both share the same parent, you can output the change to the parent and the parent will update the other child component (update an input).
  2. you could use a shared store (e.g. ng-redux).
  3. as query param using some kind of ui router (depend of the use case).
Related