Angular 6 Router重复HTML

Abr*_*ain 2 angular angular-router

我正在努力实现以下目标:

  1. 我有一个mat-toolbar组件,app.component.html用于显示网站的主要顶部导航栏。工具栏下面是<router-outlet></router-outlet>
  2. 当用户导航到localhost:4200/我的根目录时,我希望顶部导航栏可见,并且与导航栏中的链接关联的所有组件都呈现在顶部导航栏下方。
  3. 现在的问题是,当用户导航到根目录时,顶部导航栏会重复两次。单击链接,将删除重复的导航栏,并在导航栏下方呈现适当的组件(这是我希望的而无需重复)。

这里是 app.module.ts

// initialization and module imports
const RootRoutes: Routes = [
 {path: "", redirectTo: "root", pathMatch: "full"},
 {path: "root", component: AppComponent, },
 //{path: "home", component: HomeComponent },
 {path: "fiction", component: FictionDisplayComponent },
 {path: "nonfiction", component: NonFictionDisplayComponent},
 {path: 'poetry', component: PoetryDisplayComponent},
 {path: 'journal', component: JournalDisplayComponent},
 {path: 'letters', component: PersonalLetterDisplayComponent},
 {path: 'jokes', component: JokesDisplayComponent}
];
// NgModule declaration
Run Code Online (Sandbox Code Playgroud)

这里是如何app.component.html的设置:

<div class="pure-g rr-main-wrapper">
    <div class="pure-u-5-5 home-top-navbar-wrapper">
        <rr-home-top-navbar></rr-home-top-navbar>
    </div>

</div> 
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

这里是如何home-top-navbar.component.html的设置:

<mat-toolbar color="primary" class="home-top-nav">
  <mat-toolbar-row>
    <img src="./../../assets/imgs/logo2.png" width="200" height="50">
    <mat-nav-list class="home-top-nav">
      <mat-list-item *ngFor="let route of navbarRoutes">
        <a [routerLink]="[route.url]" class="navbar-link">{{ route.name }}</a>
      </mat-list-item>
    </mat-nav-list>
  </mat-toolbar-row>
Run Code Online (Sandbox Code Playgroud)

现在,如果您注意到其中有注释掉的路径{path: 'home', component: HomeComponent},我尝试单独加载工具栏,并且仅<router-outlet></router-outlet>在中app.component.html。但是,问题是当我单击链接时,页面导航到更正的组件,
顶部导航栏不再可见(这是预期的,因为其他组件没有重复导航栏代码)。

当用户导航到根目录时,是否有任何方法可以在不重复两次工具栏的情况下实现?是否可以在不复制/粘贴顶层组件的每个页面上的导航栏的情况下完成此操作?

Bun*_*ner 5

AppComponent应该不会是你的一部分Routes。这是因为,这是AppComponent您应用程序的切入点。在index.html,你有类似的东西<rr-app></rr-app>。如果有导航到AppComponent的路线(route root),则Angular会AppComponentrouter-content其中进行渲染,最终以两个为单位结束navbar

据我了解,您不需要路线root

将您的路由配置更改为以下内容。

/* 
 * Removed AppComponent and redirected "/" to "home"
 */
const RootRoutes: Routes = [
 {path: "", redirectTo: "home", pathMatch: "full"},
 {path: "home", component: HomeComponent },
 {path: "fiction", component: FictionDisplayComponent },
 {path: "nonfiction", component: NonFictionDisplayComponent},
 {path: 'poetry', component: PoetryDisplayComponent},
 {path: 'journal', component: JournalDisplayComponent},
 {path: 'letters', component: PersonalLetterDisplayComponent},
 {path: 'jokes', component: JokesDisplayComponent}
];
Run Code Online (Sandbox Code Playgroud)