How do I re-render a component manually?

你离开我真会死。 提交于 2019-11-28 23:04:46

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

    }
}

You can force angular2 to re-initialize component by navigating to some other url and then back to one you want.

Here is my simple workaround using Router class methods (reference: https://angular.io/docs/ts/latest/api/router/index/Router-class.html)

Component constructor:

constructor(private router: Router) {}

In template (example):

(click)="onTabChange(id)"

Then inside component class:

onTabChange() {
  if (this.router.navigated === false) {
    // Case when route was not used yet
    this.router.navigateByUrl(`/module/${id}`);
  } else {
    // Case when route was used once or more
    this.router.navigateByUrl(`/index`).then(
      () => {
        this.router.navigateByUrl(`/module/${id}`);
      });
  }
}

Constructor will not be called again when you are just updating the params. Because the Component class is already instantiated,

you can subscribe to params changes like below if you want to detect the change,

  constructor(route: ActivatedRoute) {
    route.params.subscribe(param => {
        let id = param['id '];
        // Do your stuff with id change.
    });
  }

Hope this helps!!

I think the changeDetectorRef is the proper tool for this job:

HTML

<my-component *ngIf="!reloading"
              (loadNext)="onLoadNext()">
</my-component>

TS

  constructor(
    private cdr: ChangeDetectorRef
  ) { }

  onLoadNext() {
      this.reloading = true;
      this.cdr.detectChanges();
      this.reloading = false;
      this.cdr.detectChanges();
  }

Why would you want this, instead of "updating the model and the view updates itself", as in the answer that Günther provided? This way you're sure the component gets reinitialized and there aren't some left over values from before. That's why I find it cleaner to do it like this.

Example: https://stackblitz.com/edit/commatrainer-v1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!