У меня есть MuscleComponent, который имеет MuscleAddComponent и MuscleEditComponent в качестве дочерних компонентов. Я пытаюсь перенаправить его дочерние компоненты, когда нажимаю на них, но вместо этого они отображаются в том же представлении MuscleComponent.
Примечание: Когда у меня { path: '', component: MusclesComponent, pathMatch: 'full' },
у детей с мышечным путем, я получаю два одинаковых HTML-сообщения MuscleComponent на той же странице. Почему это так? и почему, когда я нажимаю кнопку «Добавить», отображается содержимое MuscleAddComponent в HTML-файле MuscleComponent?
app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{
path: 'muscles', component: MusclesComponent, children: [
{ path: '', component: MusclesComponent, pathMatch: 'full' },
{ path: 'add', component: MuscleAddComponent },
{ path: ':id', component: MuscleEditComponent }
]
},
{ path: 'workouts', component: WorkoutsComponent },
{ path: 'myplanner', component: MyPlannerComponent },
{ path: '**', redirectTo: '' }
];
app.component.html
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">
<img src="../assets/images/logo.png" height="60px" style="padding: 0px; margin: 0px;">
</a>
<app-menus></app-menus>
</nav>
<router-outlet></router-outlet>
< Сильный > muscles.component.html
<div class="container-fluid">
<div class="row" style="padding: 25px;">
<div class="col-md-6">
<h2>Manage Muscles</h2>
</div>
<div class="col-md-6">
<div class="float-right">
<button type="button" class="btn btn-secondary" [routerLink]="['./add']">Add New</button>
</div>
</div>
</div>
</div>
<router-outlet></router-outlet>
Любая помощь высоко ценится.
2 ответа
Попробуйте использовать forChild
в своем muscles.module.ts
:
RouterModule.forChild([
{
path: 'muscles', component: MusclesComponent, children: [
{ path: '', component: MusclesComponent, pathMatch: 'full' },
{ path: 'add', component: MuscleAddComponent },
{ path: ':id', component: MuscleEditComponent }
]
},
])
Или если у вас нет отдельного модуля muscles.module.ts
:
const routes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'muscles', component: MusclesComponent, pathMatch: 'full'}
{ path: 'muscles/add', component: MuscleAddComponent },
{ path: 'muscles/:id', component: MuscleEditComponent },
{ path: 'workouts', component: WorkoutsComponent },
{ path: 'myplanner', component: MyPlannerComponent },
{ path: '**', redirectTo: '' }
];
Ваши маршруты работали неправильно, так как ваши компоненты, такие как MuscleAddComponent
, MuscleEditComponent
, на самом деле не дочерние. Я имею в виду, что они являются отдельными компонентами, потому что у них нет общего модуля. Так что вам не нужно использовать свойство children
. Как пример из Angular Docs:
Src / app / кризис-центр / кризис-центр-routing.module.ts (маршруты):
const crisisCenterRoutes: Routes = [
{
path: 'crisis-center',
component: CrisisCenterComponent,
children: [
{
path: '',
component: CrisisListComponent,
children: [
{
path: ':id',
component: CrisisDetailComponent
},
{
path: '',
component: CrisisCenterHomeComponent
}
]
}
]
}
];
Обратите внимание, что вышеуказанный маршрут создан в отдельном модуле .../crisis-center-routing.module.ts
.
const routes: Routes = [
{ path: '', component: HomeComponent, pathMatch: 'full' },
{
path: 'muscles', children: [
{ path: '', component: MusclesComponent },
{ path: 'add', component: MuscleAddComponent },
{ path: ':id', component: MuscleEditComponent }
]
},
{ path: 'workouts', component: WorkoutsComponent },
{ path: 'myplanner', component: MyPlannerComponent },
{ path: '**', redirectTo: '' }
];
Если вы удалите роутер-розетку из мышц. html, этот маршрут должен работать
Похожие вопросы
Новые вопросы
angular
Вопросы об Angular (не путать с AngularJS), веб-фреймворке от Google. Используйте этот тег для вопросов Angular, которые не относятся к отдельной версии. Для более старой веб-инфраструктуры AngularJS (1.x) используйте тег AngularJS.