问题
There are 2 separate modules in an Angular 5 application named as core and admin.
The core routing is set up as :
const routes: Routes = [
{
path: '',
redirectTo: 'login',
pathMatch: 'full'
},
{
path: 'admin',
loadChildren: './../admin/admin.module#AdminModule',
data: {
expectedRole: Constants.ADMIN_ROLE_ID
}
},
];
Now, within the admin module, the routing is as :
const routes: Routes = [
{
path: 'activity',
children: [
{ path: '', component: ActivityComponent },
{ path: 'detail/:id', component: ActivityDetailComponent }
]
},
{
path: 'user',
children: [
{ path: '', component: UserComponent },
{ path: 'detail/:id', component: UserDetailComponent },
]
}
];
Objective
If the application page is at "http:localhost/admin/activity"
, I need to add a routerLink to an HTML element so that the app navigates to "http:localhost/admin/user/detail/1"
.
What I have tried
[routerLink]="['user/detail', id]
but this takes the app to "http://localhost/admin/activity/user/detail/1"
.
Expected output
"http:localhost/admin/user/detail/1"
.
Please note
The admin
keyword in the route is dynamic and I do not wish to hard code this in the routerLink
.
回答1:
This issue can be resolved as changing your admin-routing.module.ts file as:
const routes: Routes = [
{
path: '',
component: AdminComponent
children: [
{
path: 'activity',
component: ActivityComponent,
children: [
{
path: 'view',
component: ActivityViewComponent
},
{
path: 'detail/:id',
component: ActivityDetailComponent
}
]
},
{
path: 'user',
component: UserComponent,
children: [
{
path: 'view',
component: UserViewComponent
},
{
path: 'detail/:id',
component: UserDetailComponent
}
]
}
]
}
];
You can see two new components: UserViewComponent and ActivityViewComponent, which simply used for the view of your current UserComponent and ActivityComponent respectively.
Replace the content of user.component.html (place it in user-view.component.html) and activity.component.html (place it in activity-view.component.html) by <router-outlet></router-outlet>
which is very important in this task.
Now you can access these components as
- /admin/activity/view
- /admin/activity/detail/:id
- /admin/user/view
- /admin/user/detail/:id
You can find more details here
回答2:
He try this one
const routes: Routes = [
{
path: 'activity',
children: [
{ path: '', component: ActivityComponent },
{ path: 'detail/:id', component: ActivityDetailComponent }
]
},
{
path: 'user',
children: [
{ path: '', component: UserComponent },
{ path: 'detail/:id', component: UserDetailComponent },
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
RouterModule.forChild(routes) use to handle other route modules
来源:https://stackoverflow.com/questions/48622082/angular-5-routerlink-between-parent-component-and-other-parent-child-component