Angular 7不会路由到新页面,但是该组件仅显示在上一个组件下

时间:2019-09-29 04:38:32

标签: angular typescript routing angular-routing

我正在尝试创建一个导航栏,当您单击其中一个小节时,它将导航您到新页面。到目前为止,当您单击导航中的一个小节时,该组件将简单地显示在主页上现有组件的下面。

这是我的app.component.html

2
abc
def

这是我的app-routing.module.ts

<nav class="navbar navbar-dark bg-dark">
  <a class="navbar-brand" routerLink="#"><img class="navBarLogo" src="../../assets/whitelogo.png"></a>
  <div class="navItemList">
    <a class="navbar navItem" routerLink="/about">Home</a>
    <a class="navbar navItem" routerLink="/about">About</a>
    <a class="navbar navItem" routerLink="/about">Scheduling</a>
    <a class="navbar navItem" routerLink="/about">Services</a>
  </div>
</nav>
<router-outlet></router-outlet>
<app-home></app-home>

例如,当我从标题中单击“关于”时,我想在页面上显示AboutComponent。但是,当您现在单击“关于”时,会发生什么,它将显示HomeComponent并在AboutComponent下。

3 个答案:

答案 0 :(得分:0)

您需要从app.component.html中删除<app-home></app-home>。并将您的路由器链接更改为“主页”按钮的<a class="navbar navItem" routerLink="/home">Home</a>

然后,您需要为root / no路径添加路径;或者,您可以在末尾添加一个包罗万象以在没有路线时捕获所有路线;但要小心,因为顺序很重要,因此必须排在最后:

const routes: Routes = [
  {path: '', component: HomeComponent },
  {path: 'home', component: HomeComponent },
  {path: 'about', component: AboutComponent},
  {path: '**', component: HomeComponent },
];

答案 1 :(得分:0)

<router-outlet></router-outlet>中,将绘制相应路线及其各自的组成部分。

请执行以下操作:

  • 从app.component.html中删除<app-home></app-home>

  • 像这样更改路由,以便在应用程序启动时(即没有路由),它指向HomeComponent

    const routes: Routes = [
      {path: '', component: HomeComponent },
      {path: 'home', component: HomeComponent },
      {path: 'about', component: AboutComponent}
    ];
    
  • 在导航列表中,像这样修改首页:<a class="navbar navItem" routerLink="/home">Home</a>

答案 2 :(得分:0)

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about/about.component'
import { CommonModule } from '@angular/common';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {path: ' ', component: HomeComponent },
  {path: 'home', component: HomeComponent },
  {path: 'about', component: AboutComponent}
];

@NgModule({
  imports: [CommonModule,
    RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

//-------------------------------------------

<nav class="navbar navbar-dark bg-dark">
  <a class="navbar-brand" routerLink="#"><img class="navBarLogo" src="../../assets/whitelogo.png"></a>
  <div class="navItemList">
    <a class="navbar navItem" [routerLink]="['home']">Home</a>
    <a class="navbar navItem" [routerLink]="['about']">About</a>
    <a class="navbar navItem" [routerLink]="['scheduling']">Scheduling</a>
    <a class="navbar navItem" [routerLink]="['Services']">Services</a>
  </div>
</nav>
<router-outlet></router-outlet>
<app-home></app-home>