我是 Angular2 的新手,我习惯了 Angular 1 的摘要循环,这意味着如果我更新 View 的范围,我可以通过调用 $scope.$digest()
。但是,我不确定如何在 Angular2 中执行此操作,尤其是考虑到新框架没有旧版本所具有的隐式数据绑定(bind)。
这是我的问题。当带有参数的 url 被命中时,我有一个加载组件的路由:
// Router
export const AppRoutes : RouterConfig = [
{
path: 'my/:arg/view',
component: MyComponent
}
]
然后我有这个组件:
// Component
export class MyComponent {
constructor(private route : ActivatedRoute,
private r : Router) {
let id = parseInt(this.route.params['value'].id);
console.log(id);
// do stuff with id
}
reloadWithNewId(id:number) {
this.r.navigateByUrl('my/' + id + '/view');
}
}
假设我导航到 url /my/1/view
。它将调用构造函数并记录数字 1
。但是,如果我使用新 ID reloadWithNewIf(2)
调用 reloadWithNewId
,则不会再次调用构造函数。如何手动重新加载组件?
最佳答案
应该不需要重新加载组件。只需更新模型, View 就会自行更新:
export class MyComponent {
constructor(private route : ActivatedRoute,
private r : Router) {}
reloadWithNewId(id:number) {
this.r.navigateByUrl('my/' + id + '/view');
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.paramsChanged(params['id']);
});
}
paramsChanged(id) {
console.log(id);
// do stuff with id
}
}
关于angular - 如何手动重新渲染组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836674/