路由就是根据不同的url地址,动态的让根组件挂载其他组件来实现一个单页面应用
一、Angular 创建一个默认带路由的项目
1. 命令创建项目
ng new angularRoute --skip-install
2. 创建需要的组件
ng g component components/news
ng g component components/home
ng g component components/product
3. 找到 app-routing.module.ts 配置路由
import { NgModule } from ‘@angular/core‘; import { Routes, RouterModule } 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 }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
路由配置成功
4. 找到 app.component.html 根组件模板 ,配置 router-outlet 显示动态加载的路由
<h1> <a routerLink="/home">首页</a> <a routerLink="/news">新闻</a> </h1> <router-outlet></router-outlet>
在找到 app-routing.module.ts 配置默认路由
//匹配不到路由的时候加载的组件 或者跳转的路由 { path: ‘**‘, /*任意的路由*/ // component:HomeComponent redirectTo:‘home‘ }
根.html
<h1> <a routerLink="/home" routerLinkActive="active">首页</a> <a routerLink="/news" routerLinkActive="active">新闻</a> </h1>
.active{
color:red;
}
原文:https://www.cnblogs.com/foremostxl/p/12958064.html