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>

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

相关推荐
支支დ3 小时前
VO by Vercel 前端特定优势:为什么它是构建 AI 应用的新范式
前端·人工智能
香芋芋圆3 小时前
AI 冲击内卷之下,普通前端如何破局?WebGIS—— 低门槛突围赛道
前端·javascript·人工智能·学习·职场发展
INS_KF4 小时前
【编程笔记】成员函数中两个 const 的区别(const Data &getData() const;)
前端·javascript·笔记
宿6744 小时前
vue3-async
前端·javascript·vue.js
YXWik65 小时前
记录前端请求接口在浏览器请求响应的Preview和Response展示的一样的问题
前端
2501_928996225 小时前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
东风破_5 小时前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
原则猫5 小时前
TS 类型工具
前端
excel6 小时前
Nuxt + Twin CSS 中宽度超过屏幕时底部出现空白的原因与解决方案
前端·javascript
计算机魔术师7 小时前
美国司法部正式站队 OpenAI,AI 训练的版权账要这么算了
前端