一,基本指令
组件、模块、路由之间的关系图:
二,创建路由项目
新建项目时带--routing后,会多生成一个app.module.ts
ng new router --routing
或者直接使用指令:
ng generate module app-routing --flat --module=app
--flat 把这个文件放进了 src/app 中,而不是单独的目录中。
--module=app 告诉 CLI 把它注册到 AppModule 的 imports 数组中。
官方参考:
https://www.angular.cn/tutorial/toh-pt5
新建两个组件以供测试:
ng g component home
ng g component product
三,配置路由:
引入组件,配置Routes(路径,组件,……)。
src\app\app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from "./home/home.component";
import {ProductComponent} from "./product/product.component";
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product',component:ProductComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
四,配置主组件
src\app\app.component.html
插座:<router-outlet></router-outlet>
用来规定路由导航的组件显示的位置。
<a [routerLink]="['/']">主页</a>
<a [routerLink]="['product']">商品</a>
<router-outlet></router-outlet>
为什么路径是一个数组("['product']"),因为可以在路由里传递参数。
五,完成基础路由
六,通过router对象导航
src\app\app.component.html
使用button的click事件绑定一个函数:
<input type="button" value="商品详情" (click)="toProductDetail()">
src\app\app.component.ts
import {Router} from "@angular/router"
引入router,在constructor中定义router,然后编写toProductDetail(),使用.navigate指定路由:
constructor(
private router:Router
){}
toProductDetail(){
this.router.navigate(['/product'])
}
七,自定义404页面
新建组件:
src\app\app-routing.module.ts
引入组件。并添加路由:
import {Page404Component} from "./page404/page404.component";
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product',component:ProductComponent},
{path:'**',component:Page404Component},
];