Angular 8-17 动态路由

动态路由是目前主流前端框架路由组件必备的功能,用于不同组件之间需要携带参数信息的跳转,比如菜单页跳转至某一项的详情页。

然而,angular 17文档中对动态路由的例子令人费解(Common routing tasks • Angular),因此笔者撰写这篇博文作文补充例子。

1.把跳转到的详情页组件注册至路由

app.routes.ts:

export const routes: Routes = [
    {path:'play/:id',component:PlayComponent},
];

2.从videoList菜单组件中跳转

videoList.component.html

@for (video of video_list; track video.id) {
    <a class="video-list-link" routerLink="/play/{{video.id}}">{{video.name}}</a>
}

videoList.component.ts: 记得引入RouterLink

import { RouterLink } from '@angular/router';
@Component({
  selector: 'app-home',
  standalone: true,
  imports: [RouterLink],
  templateUrl: './videoList.component.html',
  styleUrl: './videoList.component.css'
})

3.跳转至play组件,使用this.route.snapshot.params['参数名'] 进行接受

play.component.ts

import { ActivatedRoute } from '@angular/router';
export class PlayComponent {
    video_id=-1;
    constructor(private route: ActivatedRoute) {}
    ngOnInit() {
        this.video_id=this.route.snapshot.params['id'];
    }

references:

Angular Basics: Dynamic Activated Route Snapshots

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值