Adding routes dynamically to lazy loaded modules in Angular

AttachmentComponent route example
  • Lazy loaded modules : The router config can only be changed after the module is loaded.
  • Deep-linking : When the router starts to navigate to the URL it just does not exists yet.

Code example lazy loaded

Lazy loading of a module can be detected by subscribing to the RouteConfigLoadEnd router event. This event will be triggered after a module is lazy loaded.

app-routing.module.ts
dynamic-path.ts

Code example deep-linking

I could not find a way to freeze the router from its navigation cycle so the code in the lazy loaded section would be ready and the route would be known. If you do, please tell me! So the only solution is to catch this unknown route before its redirected to the 404 page. This is done with an canActivate guard.

Stackblitz code demo

Navigate with the buttons to the general module and then to the dynamic route for the normal dynamic insertion then hit refresh in the StackBlitz browser for the deeplink

Code in action

--

--

Freelance Senior Frontend Developer (Angular) @ www.webappdevelopment.nl

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store