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