Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional routing not working in Angular Application

In my dev build in my angular project, In the child module's routing file I am doing something like below,

const routes = window.innerWidth > 768 ? desktopRoutes: mobileRoutes;

Then I am passing these routes to RouterModule.forChild(routes)

The dev build works like a charm, however, when I create a prod build and deploy it, this thing fails to work and only loads the mobileRoutes, Irrespective of the screen resolution.

Any suggestions or alternatives I should look into are welcome

Note: that desktop route components extend Mobile components, just adding the info if that helps!

like image 673
nobalG Avatar asked Apr 28 '26 12:04

nobalG


1 Answers

It's because in prod build, AOT (Ahead of time compilation) is used, pre-compiling your routes. So, your routes return the false value: mobileRoutes.

There are some workarounds

  1. Using router: resetConfig(config) You should pass as parameter the new configuration, as described in resetConfig documentation, changing only the required routes.

  2. Using guards with CanActivate


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if( window.innerWidth > 768 ){
    return true; // return desktopRoute
  }

  this.router.navigate(['main/']);  // mobileRoute
  return false;
}
like image 131
georgeos Avatar answered May 01 '26 01:05

georgeos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!