angular入门基础教程(十二)动态路由数据传参

路由动态传参

业务场景:

  • 点解商品列表页里面的商品,根据每个商品的 id 进入详情页
  • 其他主要就是不同的类型,展示相同页面的不同数据内容

步骤一:

改造 src/app/app.config.ts,在provideRouter里面加入withComponentInputBinding()

js 复制代码
import { provideRouter, withComponentInputBinding } from '@angular/router';

registerLocaleData(zh);

export const appConfig: ApplicationConfig = {
  providers: [
    ...
    //注入路由,加入withComponentInputBinding()
    provideRouter(routes, withComponentInputBinding()),
    ...
  ],
};

步骤二:

改造src/app/app.routes.ts里面加入id参数

js 复制代码
{
    path: 'goods-detail/:id',
    component: GoodsDetailComponent,
    title: '商品详情',
  }

步骤三:

在需要使用理由跳转的页面,注入路由模块的依赖

改造src/app/components/goods-list/goods-list.component.ts

js 复制代码
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';

@Component({
  ...
  imports: [RouterModule],
  ...
})

步骤四:

改造src/app/components/goods-list/goods-list.component.html,下面两种跳转方式都行

html 复制代码
<li>
  <!-- <a routerLink="/goods-detail/{{1}}" routerLinkActive="true">啤酒</a> -->
  <a [routerLink]="['/goods-detail',1]" routerLinkActive="true">啤酒</a>
</li>

改成迭代的形式

html 复制代码
<div>
  <ul>
    @for (item of goodsList; track $index) {
    <!-- <li><a routerLink="/goods-detail/{{item.id}}">{{item.title}}</a></li> -->
    <li><a [routerLink]="['/goods-detail',item.id]">{{item.title}}</a></li>

    }
  </ul>
</div>

步骤五:

最后在详情页面进行数据的接受,展示

  • 注入路由模块的依赖,ActivatedRoute
js 复制代码
import { Component } from '@angular/core';
// 导入路由模块的依赖,ActivatedRoute
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-goods-detail',
  standalone: true,
  imports: [],
  templateUrl: './goods-detail.component.html',
  styleUrl: './goods-detail.component.css',
})
export class GoodsDetailComponent {
  goodsId = 0;
  // 注入路由模块的依赖,ActivatedRoute
  constructor(private route: ActivatedRoute) {
    this.route = route;
  }
  ngOnInit() {
    this.route.params.subscribe((params) => {
      this.goodsId = params['id'];
    });
  }
}
  • 展示数据
html 复制代码
<div>
  <h3>{{goodsId}}</h3>
  <p>goods-detail works!</p>
</div>

这样我们就实现了路由动态传参

相关推荐
liming49515 小时前
Maven中央库迁移
服务器·前端·maven
超哥--1 天前
B站视频内容智能分析系统(九):React 前端与管理面板
前端·react.js·前端框架
Cutecat_1 天前
视频字幕处理工具横向:提取模式 vs 编辑模式,该如何选择
android·前端·ios·语音识别
qq_422152571 天前
PDF 加水印工具怎么选?2026 年文档版权保护方案对比
前端·pdf·github
kyriewen1 天前
手写 Promise.all、race、any:不到 30 行代码,解决并发异步的所有姿势
前端·javascript·面试
brucelee1861 天前
OpenClaw 浏览器控制(Chrome MCP)完整教程
前端·chrome
ct9781 天前
React 状态管理方案深度对比
开发语言·前端·react
胡志辉的博客1 天前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·chrome·chromium·event loop
代码不加糖1 天前
js中不会冒泡的事件有哪些?
前端·javascript·vue.js
懂懂tty1 天前
Vue2与Vue3之间API差异
前端·javascript·vue.js