Route
const appRoutes: Routes = [
{ path: '', redirectTo: '/companies/unionbank', pathMatch: 'full'},
{ path: 'companies/:bank', component: BanksComponent },
{ path: '**', redirectTo: '/companies/unionbank' }
]
Component
const NAVBAR = [
{
name: 'Banks',
submenu: [
{ routelink: '/companies/unionbank', name: 'Union Bank' },
{ routelink: '/companies/metrobank', name: 'Metro Bank' },
{ routelink: '/companies/bdo', name: 'BDO' },
{ routelink: '/companies/chinabank', name: 'China Bank' },
]
},
...
]
Example of link: http://localhost:8099/#/companies/bdo
I want to get String
bdo in the example link above.
I'm aware that I can get the link by using window.location.href and split into array. So, I can get the last param but I want to know if there's a proper method on doing this in angular way.
Any help would be appreciated. Thanks
This question is related to
angular
angular2-routing
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
Source: Stackoverflow.com