gpt4 book ai didi

Angular 6 路由器重复 HTML

转载 作者:行者123 更新时间:2023-12-04 00:30:55 25 4
gpt4 key购买 nike

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

  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

这里是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>

这里是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>

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

当用户导航到根目录时,有什么方法可以在不重复工具栏两次的情况下实现这一点?这可以在不复制/粘贴顶级组件的每个页面上的导航栏的情况下完成吗?

最佳答案

AppComponent应该成为您的Routes 的一部分.这是因为,AppComponent是您的应用程序的入口点。在 index.html , 你有类似 <rr-app></rr-app> .如果有导航到 AppComponent 的路线(路线 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}
];

关于Angular 6 路由器重复 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51207124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com