{{announcement.body}}
{{announcement.title}}

Angular Basics: Refresh an Angular Component without reloading the same Component

DZone 's Guide to

Angular Basics: Refresh an Angular Component without reloading the same Component

A short trick for refreshing Angular components.

· Web Dev Zone ·
Free Resource

If you are working with Angular and need to refresh a component without navigation on another component without using  window.location.reload()  or  location.reload(), you can use the following code in your project:

mySubscription: any;


Then, add this code to the required component's constructor.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
  return false;
};

this.mySubscription = this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    // Trick the Router into believing it's last link wasn't previously loaded
    this.router.navigated = false;
  }
});


Make sure to unsubscribe  from this mySubscription  in  ngOnDestroy().

ngOnDestroy() {
  if (this.mySubscription) {
    this.mySubscription.unsubscribe();
  }
}

Here, we just trick the router into believing that the last link was never visited; when the button is clicked, the program will load that component (refreshing the component).

This snippet will work in Angular 2, 4, 5, 6, 7, and 8.

Topics:
typescript ,angular ,web dev ,typescript 1.6 ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}