Angular 导航内容而不更改组件

我有 2 个组件:componentA 和 componentB 当我单击 componentA 中的按钮时,这将导航到 componentB,但是 componentA 和 componentB 具有相同的过滤器和左侧边栏,唯一不同的是内容


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>

有没有办法使用 1 个组件来显示它们?


尚方宝剑之说
浏览 75回答 2
2回答

慕标5832272

上述解决方案肯定会起作用,但理想情况下,您应该使用 Angular 路由器。这就是我认为你在这里想要实现的目标。以下是您需要实施的更改:someRootComponent.html&nbsp; &nbsp; <app-new-post></app-new-post>&nbsp; &nbsp; <app-filter-forum></app-filter-forum>&nbsp; &nbsp; <router-outlet></router-outlet>此时你可以摆脱ComponentA和componentB。您的路线如下所示:const routes: Routes = [&nbsp; { path: 'view-topic', component: ViewTopicComponent },&nbsp; { path: 'sub-topic', component: SubTopicComponent },&nbsp; { path: '**', component: PageNotFoundComponent },&nbsp; // Wildcard route for a 404 page];您最终会遇到的问题是管理状态。有很多方法可以处理这个问题。如果您想支持深度链接,那么我建议您这样做:const routes: Routes = [&nbsp; { path: 'view-topic/:topicId', component: ViewTopicComponent },&nbsp; { path: 'sub-topic/:subTopicId', component: SubTopicComponent },&nbsp; { path: '**', component: PageNotFoundComponent },&nbsp; // Wildcard route for a 404 page];这是链接到主题的方式:&nbsp; <a [routerLink]="['/view-topic', topic.id]">Angular 路由器文档非常好,可以在这里找到: Angular Router Docs

MMTTMM

您可以使用 ngIf 检查以显示不同的 domComponentA.html&nbsp; &nbsp; <app-new-post></app-new-post>&nbsp; &nbsp; <app-filter-forum></app-filter-forum>&nbsp; &nbsp; <app-view-topic [topicData]="viewContent" *ngIf="!showBComponent"&nbsp; &nbsp; &nbsp; &nbsp; (showSubTopic)="onShowSubTopic($event)"></app-view-topic>&nbsp; &nbsp; <app-sub-topic *ngIf="showBComponent "></app-sub-topic>ComponentA.ts&nbsp; &nbsp; let showBComponent: boolean = false;&nbsp; &nbsp; onShowSubTopic(e: any): void {&nbsp; &nbsp; &nbsp; &nbsp; this.showBComponent = true;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript