游乐游手机版
首页/前端开发/文章详情

Angular路由从入门到实战详解

时间:2026-06-13 06:45
1 使用 routerLink 指令 路由跳转 项目创建从一行命令开始: ng new ng-demo 然后是组件创建,这一步通常不会少: ng g component components home ng g component components news ng g component com

1 使用 routerLink 指令 路由跳转

项目创建从一行命令开始:

Angular 中的路由详解

ng new ng-demo

然后是组件创建,这一步通常不会少:

ng g component components/home
ng g component components/news
ng g component components/produect

自然要做的第一步,就是在 app-routing.module.ts 中把路由配置好。先引入组件:

import { HomeComponent } from './components/home/home.component';
import { NewsComponent } from './components/news/news.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'}
];

根组件的模板里,用 router-outlet 来显示动态加载的路由内容,这是最基础的做法:

首页 新闻

routerLink 负责跳转,而默认路由用 redirectTo 就能处理匹配不到的情况:

//匹配不到路由的时候加载的组件 或者跳转的路由
{path: '**', redirectTo: 'home'}

routerLinkActive 用来给当前选中的路由加个高亮样式,比如:

首页 新闻

.active { color: green; }

这里也可以换成数组绑定的写法,效果是一样的:

首页 新闻

2 使用方法跳转路由 - 使用 router.na vigate 方法

除了指令,还能在组件里通过注入 Router 服务,调用 na vigate 方法来实现编程式跳转:

import { Component } from '@angular/core';
import { Router} from "@angular/router";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = "routerProject";
  constructor(public router: Router) {
  }
  goToPage(path: string) {
    this.router.na vigate([path]).then(r => {})
  }
}

模板里配合按钮点击事件即可:

3 routerLink跳转页面传值 - GET传值的方式

页面跳转的同时,经常需要顺带传些参数。queryParams 就是用来干这个的,写法也很直观:

首页 新闻

接收参数的地方,就得靠 ActivatedRoute 了:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit{
  constructor(public activatedRoute: ActivatedRoute) {
  }
  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(data => {
      console.log(data)
    })
  }
}

4 使用方法跳转页面传值 - GET传值的方式

如果用编程式跳转,传参方式也类似,只是把参数放在了 na vigate 的第二个参数里:

import { Component } from '@angular/core'; import { Router} from "@angular/router"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = "routerProject"; constructor(public router: Router) { } goToPage(path: string, param: string) { this.router.na vigate([path], { queryParams: { name: param } }).then(r => {}) } }

5 动态路由的方式 - 路由跳转

动态路由的做法,是在路由配置里加个 :id 这样的占位符:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {HomeComponent} from "./components/home/home.component";
import {NewsComponent} from "./components/news/news.component";
import {ProductComponent} from "./components/product/product.component";
const routes: Routes = [
  {path: 'home/:id', component: HomeComponent},
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

页面设置参数时,把值放在数组里即可:

首页

接收动态参数的写法稍有不同,用的是 params 而不是 queryParams

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit{
  constructor(public activatedRoute: ActivatedRoute) {
  }
  ngOnInit(): void {
    this.activatedRoute.params.subscribe(data => {
      console.log(data)
    })
  }
}

6 父子路由

父子里由的场景也很常见,比如在一个页面里再嵌套另一个路由。先创建好组件并引入:

import {HomeComponent} from "./components/home/home.component";
import {NewsComponent} from "./components/news/news.component";

然后在路由配置里用 children 来组织:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {HomeComponent} from "./components/home/home.component";
import {NewsComponent} from "./components/news/news.component";
const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    children: [
      {
        path: 'news',
        component: NewsComponent
      },
      {path: '**', redirectTo: 'home'}
    ]
  },
  {path: '**', redirectTo: 'home'}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

父组件模板里也要放一个 router-outlet,用来显示子路由的内容:

来源:https://www.jb51.net/javascript/304242q6d.htm
上一篇Angular6拖拽指令Drag实例详解 下一篇Angular 同一路由跳转时组件重新执行的实现方法
本站内容用于信息整理与展示,如有侵权或内容问题请及时联系处理。

相关推荐

补充同频道和同主题内容,方便继续浏览更多相关内容。

同类最新

继续查看同栏目最近更新的文章。

更多
Layui弹出层监听子页面键盘快捷键实现方法
前端开发 · 2026-07-06

Layui弹出层监听子页面键盘快捷键实现方法

子页面键盘事件监听需在DOM加载完成后绑定,父页无法直接监听子页按键,必须由子页自身监听后通过parent或postMessage通知父页。典型写法为子页调用父页已定义的关闭函数。需注意焦点状态、输入法及layui版本兼容性等陷阱。

Layui表单提交时携带当前页面Meta信息的实现方法
前端开发 · 2026-07-06

Layui表单提交时携带当前页面Meta信息的实现方法

Layui表单提交不会自动携带页面Meta信息,需在form on( submit )回调中手动读取meta内容并拼接到表单数据,注意后端字段映射及特殊字符编码,多meta时按需选取。

HTML5拖拽事件流状态转移监控调试
前端开发 · 2026-07-06

HTML5拖拽事件流状态转移监控调试

HTML5拖拽事件流易因漏监听或未调用preventDefault而中断。需掌握dragstart设置数据、dragover接受放置、drop触发条件等关键点。通过统一日志捕获事件上下文、识别常见状态丢失场景并配合可视化面板,可清晰定位拖拽过程断点。

uni-app实现小红书商品详情图卡片切换
前端开发 · 2026-07-06

uni-app实现小红书商品详情图卡片切换

通过手写touch事件与transform控制五张卡片,动态计算translateX、scale、opacity及z-index模拟层叠滑动效果。滑动距离超过80rpx触发切换,否则复位。图片仅渲染当前及前后两张,有效优化加载性能与渲染效率。

图像旋转倾斜与扭曲的Canvas像素矩阵变换
前端开发 · 2026-07-06

图像旋转倾斜与扭曲的Canvas像素矩阵变换

Canvas图像变形本质是操作坐标系,图像被动跟随。旋转需先平移原点至目标中心再旋转后复位;倾斜通过仿射变换矩阵实现;扭曲无原生API,可用分块模拟或转用WebGL。每次变换前保存状态,完成后恢复,避免坐标系偏移。