In this tutorial, we will see what are the different ways to Pass Data From Routes To Components In Angular 10.
In other words like sending data from anchor tags or routing module files of angular other than query params.
Pass Data From Routes (Static Data)
For passing the static data (via the routing module) below example can be implemented.
Send data through Routes
For example, if the route can be accessed for particular user roles we can define in routes data and that roles can be retrieved inside the component.
{
path: 'dashboard',
loadChildren: loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
data: { userRoles: [UserRoles.SELLER, UserRoles.SUPER_ADMIN, UserRoles.DATA_MANAGER] }
}
The Angular Router will pass the defined roles when the dashboardModule
is rendered. The data will be located in the data property of the ActivatedRoute service.
Access data from Routes
For getting data from the route we can subscribe to the data property of the ActivatedRoute
class which will contain data we send from the Routing Module.
public ngOnInit(): void {
this.activatedroute.data.subscribe(data: UserRoles[] => {
this.roles = data.userRoles as UserRoles[];
});
}
Pass Data From Routes (Dynamic Data)
For passing the dynamic data to routes (via component) below example can be implemented.
The option for passing the dynamic data or a user-defined object was implemented in the Angular Version 7.2 using the state object. The state object is stored in the History API.
The state can be provided in two ways:
1: Using routerLink
directive
<a [routerLink]="['dashboard']" [state]="{ id:1 , role:'super_admin'}">
Dashboard
</a>
2: Using navigateByUrl
method
// value which can be set dynamically
public user: {id: string, role: string} = { id:1 , role:'super_admin' };
// on click action
this.router.navigateByUrl('/dashboard', { state: this.user });
Accessing the state value
The state can be accessed in three different ways:
1: Using getCurrentNavigation
method
this.router.getCurrentNavigation().extras.state
getCurrentNavigation
method will only work in constructor.2: Using history.state
in ngOnInit
console.log(history.state) // browser property
3: Using getState
in Location
service
import { Location } from '@angular/common';
export class SomeComponent implements OnInit {
public user: {id: string, role: string};
constructor(private location:Location){}
public ngOnInit(): void {
this.user = this.location.getState();
}
}
getState
method is available Angular 8+