# 路由的作用

路由就是根据不同 url 地址,动态地让根组件挂载其他组件来实现一个单页面应用。

# 路由的使用

  1. 创建一个带路由的项目,第一个选择选 y
ng new angulardemo11
  1. 创建需要的组件
ng g component components/home
ng g component components/news
ng g component components/product
  1. 跟模块引入组件并注入
  2. 路由模块引入组件并在 routes 里面配置 path 和 component
  3. 根页面引入 <router-outlet> 标签
  4. 使用 routerLink 跳转,可以通过 routerLinkActive 设置 active 样式

# 完整代码

# app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewsComponent } from './components/news/news.component';
import { HomeComponent } from './components/home/home.component';
import { ProductComponent } from './components/product/product.component';
@NgModule({
  declarations: [
    AppComponent,
    NewsComponent,
    HomeComponent,
    ProductComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

# app.component.scss

.header{
    height: 44px;
    line-height: 44px;

    background-color: #000;
    color: #fff;

    a{
        color: #fff;
        padding: 10px 40px;
    }

    .active{
        color: red;
    }
}

# app.component.html

<header class="header">
  <!-- <a [routerLink]="[ '/home' ]"> 首页 & lt;/a>
  <a routerLink="/news"> 新闻 & lt;/a>
  <a [routerLink]="[ '/product' ]"> 商品 & lt;/a> -->
  <a [routerLink]="[ '/home' ]" routerLinkActive="active">首页</a>
  <a routerLink="/news" routerLinkActive="active">新闻</a>
  <a [routerLink]="[ '/product' ]" routerLinkActive="active">商品</a>
</header>
<router-outlet></router-outlet>

# app-routing.module.ts

// 配置路由的模块
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NewsComponent } from './components/news/news.component';
import { HomeComponent } from './components/home/home.component';
import { ProductComponent } from './components/product/product.component';
const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent
  },
  {
    path: 'news',
    component: NewsComponent
  },
  {
    path: 'product',
    component: ProductComponent
  },
  {
    path: '**',  // 任意路由,默认跳转到 home 页面
    redirectTo: 'home'
  }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }