angular - Angular 6 路由器重复 HTML
问题描述
我正在努力实现以下目标:
- 我有一个
mat-toolbar
组件,app.component.html
它显示站点的主要顶部导航栏。工具栏下方是<router-outlet></router-outlet>
. - 当用户导航到根目录时,
localhost:4200/
我希望顶部导航栏可见,并且与导航栏中的链接关联的所有组件都在顶部导航栏下呈现。 - 现在的问题是,当用户导航到根目录时,顶部导航栏会重复两次。单击链接,重复的导航栏被删除,并在导航栏下呈现正确的组件(这是我想要的,没有重复)。
这里是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 将AppComponent
在router-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}
];
推荐阅读
- r - 使用 R 根据子字符串的第 n 次出现有效地分解字符串
- wordpress - 为 Wordpress 中的每个帖子自动创建的民意调查
- amazon-web-services - 如何指向 ALB 的 hesos 而不是 rightscale?
- json - Inno Setup:如何从 JSON 文件的子部分编辑和检索值
- qt - QML - 如何让孩子进入项目?
- python - user.is_authenticated 不能用于生产
- rest - 卡在从 QlikSense 中的 SurveyMonkey REST Connection 获取调查详细信息
- c# - DCMTK:从 C# 调用的包装 dcmsend dll 在多次调用时会出错
- android - 修改从 Room 获取的 LiveData 项
- html-email - font-weight inline 在某些 Outlook for Windows 中使用将 sans-serif 字体更改为 serif