I have encountered an issue while attempting to execute a TypeScript expression within the router module of my Angular application. The expression I am trying to evaluate is as follows:
const check: any = window.innerWidth > 600 ? RouteOneComponent : RouteTwoComponent;
Despite the condition, it consistently routes to the RouteOneComponent
, even when the value of window.innerWidth
is below 600.
To replicate this behavior, I created a simple application and below is the code from my router module:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RouteOneComponent } from "./route-one/route-one.component";
import { RouteTwoComponent } from "./route-two/route-two.component";
const check: any = window.innerWidth > 600 ? RouteOneComponent : RouteTwoComponent;
const routes: Routes = [
{ path: 'web', component: RouteOneComponent },
{ path: 'mob', component: RouteTwoComponent },
//tried this - didn't work after build
{ path: 'check', component: window.innerWidth > 600 ? RouteOneComponent : RouteTwoComponent }
//also tried this - didn't work after build
{ path: 'check', component: check }
//also tried this - didn't work after build
{ path: 'check', component: (() => {return window.innerWidth > 600 ? RouteOneComponent : RouteTwoComponent})() }
//also tried removing the above anonymous function to a named function
//gave error during template compile, function calls not supported in decorators
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
While it functions correctly on my local machine, building the application with ng build --prod=true
causes the expression to default to true and always load the RouteOneComponent
, even on mobile devices when accessing localhost:4200/check
.
Is there a TypeScript configuration (ts-config.json
) that may be causing this behavior? What steps should I take to debug and resolve this issue, considering it only occurs post-build and not locally?