我有一个带有侧边栏的app.component。当加载 app.component 时,我从后端的数据动态构建侧边菜单。单击侧菜单中动态生成的链接之一时,我想加载组件并基于该参数构建内容。我的第一个想法是使用routerLink:
app.component:
<div>
<div *ngFor="let menuItem of menuItems" [routerLink]="['/assets',menuItem]">{{menuItem}}</div>
</div>
然后在组件的构造函数中订阅这些参数。但是,我意识到单击每个链接时不会调用构造函数(正确,因为 Angular 知道组件已准备就绪(。
做这样的事情的正确方法是什么?我是 Angular 的新手,所以请随时添加片段或链接到示例。
-
您的路由必须在 app.module.ts 文件中注册(以便您可以在您的组件中访问 menuItem 值(:
Router.forRoot( [ { path: 'assets/:menuItem', component: YourComponent } ] )
-
订阅活动:
constructor( private route: ActivatedRoute, private router: Router) {} ngOnInit() { this.sub = this.route .queryParams .subscribe(params => { params['menuItem']; }); }