DEV Community

chuac
chuac

Posted on

Updating Angular routes at runtime

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 },
];
Enter fullscreen mode Exit fullscreen mode

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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

And you're done!

Top comments (0)