如何手动重新渲染组件? [英] How do I re-render a component manually?

查看:37
本文介绍了如何手动重新渲染组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular2 的新手,我已经习惯了 Angular 1 摘要循环,这意味着如果我更新视图的范围,我可以通过调用 $scope.$digest()<手动触发摘要/代码>.但是,我不确定如何在 Angular2 中执行此操作,尤其是考虑到新框架没有旧版本所具有的隐式数据绑定.

I'm a newcomer to Angular2, I'm used to the Angular 1 digest cycle, meaning if I update the scope of a view I can manually trigger a digest by calling $scope.$digest(). However, I'm not sure how to do this in Angular2, esp given that the new framework doesn't have the implicit data binding that the old version had.

这是我的问题.我有一个路由,当一个带有参数的 url 被命中时加载一个组件:

Here's my problem. I have a route that loads a component when a url with a parameter is hit:

// 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,则不会再次调用构造函数.如何手动重新加载组件?

Lets say I navigate to url /my/1/view. It will call the constructor and the number 1 is logged. However, if I call reloadWithNewId with a new id, reloadWithNewIf(2), the constructor is not called again. How do I manually reload the component?

推荐答案

应该不需要重新加载组件.只需更新模型,视图就会自行更新:

There shouldn't be a need to reload the component. Just update the model and the view updates itself:

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

    }
}

这篇关于如何手动重新渲染组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆