# 路由的作用
路由就是根据不同 url 地址,动态地让根组件挂载其他组件来实现一个单页面应用。
# 路由的使用
- 创建一个带路由的项目,第一个选择选 y
- 创建需要的组件
| ng g component components/home |
| ng g component components/news |
| ng g component components/product |
- 跟模块引入组件并注入
- 路由模块引入组件并在 routes 里面配置 path 和 component
- 根页面引入 <router-outlet> 标签
- 使用 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="/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: '**', |
| redirectTo: 'home' |
| } |
| ]; |
| |
| @NgModule({ |
| imports: [RouterModule.forRoot(routes)], |
| exports: [RouterModule] |
| }) |
| export class AppRoutingModule { } |