我有两个组成部分:componentA和componentB当我单击componentA中的按钮时,它将导航到componentB,但是componentA和componentB具有相同的过滤器和左侧边栏,唯一不同的是content
ComponentA.html
<app-new-post></app-new-post>
<app-filter-forum></app-filter-forum>
<app-view-topic [topicData]="viewContent"
(showSubTopic)="onShowSubTopic($event)"></app-view-topic>
ComponentA.ts
onShowSubTopic() {
this.router.navigate([ComponentB])
}
ComponentB.html
<app-new-post></app-new-post>
<app-filter-forum></app-filter-forum>
<app-sub-topic></app-sub-topic>
有没有办法使用一个组件同时显示两个组件?
ComponentA.html
<app-new-post></app-new-post>
<app-filter-forum></app-filter-forum>
<app-view-topic [topicData]="viewContent" *ngIf="!showBComponent"
(showSubTopic)="onShowSubTopic($event)"></app-view-topic>
<app-sub-topic *ngIf="showBComponent "></app-sub-topic>
ComponentA.ts
let showBComponent: boolean = false;
onShowSubTopic(e: any): void {
this.showBComponent = true;
}
这里是您需要实施的更改:
someRootComponent.html
<app-new-post></app-new-post>
<app-filter-forum></app-filter-forum>
<router-outlet></router-outlet>
此时,您可以摆脱ComponentA和componentB。您的路线如下所示:
const routes: Routes = [ { path: 'view-topic', component: ViewTopicComponent }, { path: 'sub-topic', component: SubTopicComponent }, { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ];
您最终会遇到的问题是管理状态。有很多方法可以解决这个问题。如果您想支持深层链接,那么我建议您这样做:
const routes: Routes = [ { path: 'view-topic/:topicId', component: ViewTopicComponent }, { path: 'sub-topic/:subTopicId', component: SubTopicComponent }, { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ];
这是您链接到主题的方式:
<a [routerLink]="['/view-topic', topic.id]">
Angular路由器文档非常出色,可以在这里找到:Angular Router Docs