快速入门

创建跟路由模块

  1. // app-routing.module.ts
  2. import { NgModule } from '@angular/core';
  3. import { RouterModule, Routes } from '@angular//router';
  4. const routes: Routes = [];
  5. @NgModule({
  6. declarations: [],
  7. imports: [RouterModule.forRoot(routes)],
  8. exports: [RouterModule],
  9. })
  10. export class AppRoutingModule {}

创建组件测试
ng generate component components/demo1
ng generate component components/demo2
ng generate component components/demo3
ng generate component components/PageNotFound

定义路由规则

  1. const routes: Routes = [
  2. { path: 'demo1', component: Demo1Component },// 跳转到组件
  3. { path: 'demo2', component: Demo2Component },
  4. { path: 'demo3', component: Demo3Component },
  5. { path: '', redirectTo: 'demo', pathMatch: 'full' }, // 首页重定向到demo组件
  6. { path: '**', component: PageNotFindComponent }, // 通配符路由
  7. ];

模板

  1. <h1>app</h1>
  2. <ul>
  3. <li><a [routerLink]="['/demo1']" routerLinkActive="active">demo1</a></li>
  4. <li><a [routerLink]="['/demo2']" routerLinkActive="active">demo2</a></li>
  5. <li><a [routerLink]="['/demo3']" routerLinkActive="active">demo3</a></li>
  6. </ul>
  7. <br>
  8. <router-outlet></router-outlet>

后退功能

在需要后退的模板添加一个按钮,并绑定事件

  1. <button (click)="goBack()">go back</button>

在组件类中添加依赖,注入依赖,设置事件

  1. import { Location } from '@angular/common';
  2. constructor(private location: Location) {}
  3. goBack(): void {
  4. this.location.back();
  5. }

路由之间传值

路由传值

0.先在组件中初始化一个参数

  1. // app/demo1/demo1.component.ts
  2. // 模拟学生数据
  3. students: { id: number; name: string }[] = [];
  4. ngOnInit(): void {
  5. // 生成10个学生数据
  6. for (let i = 10; i < 20; i++) {
  7. this.students.push({ id: i, name: `学生${i}` });
  8. }
  9. }

1.配置路由

  1. const routes: Routes = [
  2. { path: 'demo2/:no', component: Demo2Component },
  3. ];

2.配置模板

  1. <p>demo1 works!</p>
  2. <ul>
  3. <li *ngFor="let item of students;let i = index">
  4. <a [routerLink]="[ '/demo2', item.id ]">{{i}} : {{item.name}}</a>
  5. </li>
  6. </ul>

3.在跳转到的组件中接收数据

  1. // app/demo2/demo2.component.ts
  2. // 导入依赖
  3. import { ActivatedRoute } from '@angular/router';
  4. // 依赖注入
  5. constructor(public route: ActivatedRoute) {}
  6. // 获取值
  7. ngOnInit(): void {
  8. this.route.params.subscribe((param) => {
  9. console.log(param);
  10. });
  11. }

js跳转路由

动态路由

  1. // 引入模块
  2. import { Router } from '@angular/router';
  3. constructor(public router: Router) {}
  4. // 跳转
  5. navigateByUrl
  6. this.router.navigate(['/demo']); // 普通路由
  7. this.router.navigate(['demo','1234']); // 动态路由