可以使用ActivatedRoute
的params
属性监听路由参数的变化,并手动触发组件的变化检测。可以在组件的构造函数中注入ActivatedRoute
,并使用subscribe
方法监听参数的变化。具体代码示例如下:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
paramValue: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.paramValue = params['id'];
});
}
}
在模板中使用paramValue
变量即可。这样,在路由参数变化时,组件也会随之更新。