DEV Community

chuac
chuac

Posted on

1

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay