Often, we face the problem of data sharing in Angular. Data sharing when the component are in Parent-Child or Child-Parent can be done using input , output, ViewChild & EventEmitter. But when it comes to two component which has no relation between each other.The common technique we use is creating a shared Service.

Framework such as React uses state to share data between unrelated components. Angular 7.2 now support this technique to share data. We will using the same technique to share data which reduces a lot of codes. Mainly, reducing our development time.

<a routerLink="/" [state]="{ data: 'value' }">Click here</a>
this.router.navigate(['/'], { state: { data: 'value' } });
Note: the state must be an object.

Retrieve the state data

After the data is passed, to retrieve the data we must catch the data from NavigationStartEvent.

// Get NavigationStart
router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {
  const navigation = router.getCurrentNavigation();
  const data = navigation.extras.state.data ;
});

In the above code, we retrieved the state data using NavigationStart Event thus, reducing shared Service code & less code obviously :)

We can see how easily we retrieved the data using state. Routerlink passes a parameter state which can be catch using NavigationStart Event.