There may be times where you need to update your Angular routes dynamically depending on the result of an API call, cookies, etc.
Realistically, this should be done during Angular app initialization (especially so if the routes are dependent on an API call) but we simply choose the AppModule
constructor for this quick example.
Say you have a bunch of routes that have been registered:
const routes: Routes = [
{ path: 'about-us', component: AboutUsComponent },
{ path: '', component: HomeComponent },
];
and depending on some condition at runtime, you would like to swap the base path ''
route to point to another component like NewHomeComponent
, you can do like below and access resetConfig()
on the Angular Router
:
export class AppModule {
constructor(
private readonly router: Router,
) {
if (someCondition) {
const configRoutes = this.router.config;
const index = configRoutes.findIndex((route: Route) => route.path === '');
configRoutes[index] = { path: '', component: NewHomeComponent };
this.router.resetConfig(configRoutes);
}
}
}
And you're done!
Top comments (0)