I am looking for a way to have different routing for mobile and desktop resolution. I have mater detail page layout. So when the user moves to mobile, user should see master list & when user clicks item of the list, it should navigate to the details page. I am thinking there will be 2 sets of routes for desktop and mobile & I will need to load correct route config based on width.
Please suggest.
For desktop:
const appDesktopRoutes:Routes =[
{
path: '',
component: ItemListComponent,
children: [
{
path: 'item/:id',
component: ItemDetailsComponent
}
]
}]
For Mobile :
const appMobileRoutes:Routes =[
{
path: '',
component: ItemListComponent,
},
{
path: 'item/:id',
component: ItemDetailsComponent
}
]
You can get the width of your window like below, Once you have them you can use it to hide your detail component in template, and update your detail list click behaviour, to navigate rather opening in the same page.
export class AppComponent {
constructor(ngZone: NgZone) {
// Initial draw
this.drawPage(window.innerWidth);
// On resize
window.onresize = (e) => {
ngZone.run(() => {
this.drawPage(window.innerWidth);
});
};
}
drawPage(width){
// use width to determine how to draw.
}
}
Update:
You need to reset routes based on the width.
try below,
create a Resolution service which can give you window width,
ResolutionService
@Injectable()
export class ResolutionService {
constructor(ngZone: NgZone) {
// On resize
window.onresize = (e) => {
ngZone.run(() => {
this.width.next(window.innerWidth);
});
};
}
width: BehaviorSubject<number> = new BehaviorSubject<number>(window.innerWidth);
}
Use above service in your RouterModule to reset route like below,
AppRoutingModule
const appDesktopRoutes: Routes = [
{
path: '',
component: ItemListComponent,
children: [
{
path: 'item/:id',
component: ItemDetailsComponent
}
]
}
];
const appMobileRoutes: Routes = [
{
path: '',
component: ItemListComponent,
},
{
path: 'item/:id',
component: ItemDetailsComponent
}
];
@NgModule({
imports: [
RouterModule.forRoot(appDesktopRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {
MOBILE_WIDTH = 500;
constructor(router: Router, resolutionService: ResolutionService) {
// subscribe to resolution service to get current width
resolutionService.width.subscribe(width => {
if (width < this.MOBILE_WIDTH) {
router.resetConfig(appMobileRoutes);
} else {
router.resetConfig(appDesktopRoutes);
}
});
}
}
Here is the example Plunker!!
Hope this helps!!