Reputation: 41
I am upgrading an Angular 2 app from 2.0.0-beta.0 to 2.4
I have complex routing, with many reused Components that have multiple children; I will give a simplified example:
└─Home
├─Company
| ├─Requests
| └─Users
| ├─Subscriptions
| | └─Requests
| └─Requests
├─Users
| ├─Subscriptions
| | └─Requests
| └─Requests
└─Subscriptions
└─Requests
As you can see, the Users component, and the Subscriptions component (with respective children) are used multiple times, and the Request module is also a child of Users and Company separately.
This was simple in Beta 0, as Components could have their own separate routing. However I have been unable to find a good way to do this in the current version of Angular. I could turn every reused component with children into a module with a bootstrapped component, but that adds much more code and will not be very flexible.
Is there a way to do this without making each reused component that has children a module?
Upvotes: 3
Views: 4308
Reputation: 41
I solved this by putting this code in each of my components:
in foo.component.ts:
import { BarComponent } from './bar.component'
export const FooRouting: Routes = [
{ path: 'Bar', component: BarComponent }
]
and in home.ts (the module)
import { FooComponent, FooRouting } from './foo.component'
import { BarComponent } from './bar.component'
@NgModule({
imports: [
...
RouterModule.forRoot([
{ path: '', component: FooComponent, children: FooRouting }
{ path: 'Bar', component: BarComponent }
])
...
],
...
)}
to make:
└─Home
├─Foo
| └─Bar
└─Bar
Upvotes: 1
Reputation: 1049
What about simply using 'children' + 'redirectTo'?
const routes: Routes = [
{ path: '', pathMatch: 'full', component: HomeComponent },
{ path: 'company', children: [
{ path: '', pathMatch: 'full', component: CompanyComponent},
// path '/company/requests' will redirectTo '/requests'
{ path: 'requests': redirectTo: '/requests' },
{ path: 'users': redirectTo: '/users' },
]},
{ path: 'users', children: [
{ path: '', pathMatch: 'full', component: UsersComponent },
{ path: 'subscriptions', redirectTo: '/subscriptions' },
{ path: 'requests', redirectTo: '/requests' }
]},
{ path: 'subscriptions', children: [
{ path: '', pathMatch: 'full', component: SubscriptionsComponent },
{ path: 'requests', redirectTo: '/requests' },
]},
{ path: 'requests', component: RequestsComponent },
];
Upvotes: 2