smyk
smyk

Reputation: 371

Conditional routing configuration

I would like to have a responsive application. It should have a different navigation on a small screen (series of screens to drill down to detail page) and on a big screen (left panel + details on a single page).

In effect, I would like to load different components and have a different routing configuration depending on the screen/window size. And I would like to be able to switch between them dynamically, as the window is resized above/below a certain threshold.

Since routing in Angular2 is defined on a component level, my idea was to create a root-level component, which would conditionally (ngIf) include either bigScreen.component.ts or smallScreen.component.ts. The routing itself would then be defined in bigScreen/smallScreen components. This does not seem to work though.

I created a plunk to showcase. It's basically a copy of heroes navigation from the Angular tutorial. I created additional component app/container.component.ts which is bootstraped as a root component. It then embeds AppComponent (root component in the tutorial), which contains the routing configuration.

This produces an error on the console:

Error: Component "AppContainer" has no route config.

Looks like I have to create navigation config in my root component if the nested components have one. Is there a way around it to achieve what I need? Or should the responsive routing be implemented differently?

Upvotes: 1

Views: 2077

Answers (2)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658017

In the new router (>= RC.3) https://angular.io/docs/js/latest/api/router/index/Router-class.html#!#resetConfig-anchor resetConfig can be used

router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ] }
]);

You might need a dummy configuration to initialize the router on app startup or use How to pass parameters rendered from backend to angular2 bootstrap method to delay the initialization until the route configuration is prepared.

https://github.com/angular/angular/issues/11437#issuecomment-245995186 provides an RC.6 Plunker

Upvotes: 4

Gaurav Mukherjee
Gaurav Mukherjee

Reputation: 6335

let routeMobile = [{path:'/', name: 'Home', component: MobileHomeComponent},
  {path:'/hero/:id',      name: 'Detail',   component: detailComponent}];

let routeDesktop = [{path:'/', name: 'Home', component: DesktopComponent}]

function checkForMobile(){
  //returns true for mobile
}
let finalRoute = checkForMobile() ?  routeMobile : routeDesktop;  

@Component({ ... })
@RouteConfig(finalRoute)
export class AppComponent { }

If you desperately want it to be responsive too, just reload the page on "resize" event.

Upvotes: 0

Related Questions