Angular2 Routing: persisting route tabs and child routes
I understand you have two different questions:
1- How to prevent the destruction of the component when you leave it.2- implementing child routes.
1) For now Angular doesn't have convenient way to do this. We would apreciate it if they were a life cycle hook called like canDestroy().
Anyway you can do this either using non routable tabs OR just store your data on a higher component that doesn't get destroyed.
2) For the child routes I'll just put 2 examples:
Ex1: regular child routing
const AdminRoutes: Routes = [{ path: '', component: AdminComponent, children: [ { path: 'users', component: UsersComponent, children: [ { path: 'acces', component: AccesComponent, data: { preload: true} }, { path: 'roles', component: RolesComponent, data: { preload: true} }, { path: '', redirectTo: '/admin/users/acces', pathMatch: 'full' }, { path: '**', redirectTo: '/admin/users/acces', pathMatch: 'full' }, ], data: { preload: true} }, { path: '', redirectTo: '/login', pathMatch: 'full' }, { path: '**', redirectTo: '/login', pathMatch: 'full' } ]},
EX2: When the child routes belongs to another module
Code for higher module
`
const appRoutes: Routes = [ { path: 'login', component: LoginComponent, data: { preload: true} }, { path: 'admin', loadChildren: 'app/modules/admin/admin.module#AdminModule', canActivate: [AuthGuardService], data: { preload: true} }, { path: '', redirectTo: '/login', pathMatch: 'full' }, { path: '**', redirectTo: '/login', pathMatch: 'full' }
`
Code for child routes in their own module
`
const AdminRoutes: Routes = [{ path: '', component: AdminComponent, children: [ { path: 'users', component: UsersComponent, children: [ { path: 'acces', component: AccesComponent, data: { preload: true} }, { path: 'roles', component: RolesComponent, data: { preload: true} }, { path: '', redirectTo: '/admin/users/acces', pathMatch: 'full' }, { path: '**', redirectTo: '/admin/users/acces', pathMatch: 'full' }, ], data: { preload: true} }, { path: '', redirectTo: '/login', pathMatch: 'full' }, { path: '**', redirectTo: '/login', pathMatch: 'full' } ]},
`