How to reload current page?

A little bit tricky to do something so simple but had no luck trying to reload and recreate the entire parent & child components with current solution.

Angular Router now provides strategy configuration to tell the Router what to do in case you navigate to the same URL as this user suggests in this GitHub issue.

First of all you can configure what to do while setting up the Router (your router module).

@NgModule({
   imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
   exports: [RouterModule]
})

Or, if you are like me and don't want to change the entire router module behaviour you can do it with a method/function like this:

reloadComponent() {
    this._router.routeReuseStrategy.shouldReuseRoute = () => false;
    this._router.onSameUrlNavigation = 'reload';
    this._router.navigate(['/same-route']);
}

Of course you have to first inject Router in your component's constructor:

// import { Router } from '@angular/router';
...
constructor(private _router: Router){}
...

Somehow and as pointed out by @Abhiz you have to set shouldReuseRoute, with just configuring the Router by itself the page reload doesn't work with this aproach.

I've used an arrow function for shouldReuseRoutebecause new TSLint rules won't allow non-arrow functions.


It will work 100%. The following lines of code are responsible for page reload in my project.

load(val) {
if (val == this.router.url) {
  this.spinnerService.show();
  this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };
 }
}

Just use the following part in your code.

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

This is the most simple solution if you just need to refresh the entire page

   refreshPage() {
    window.location.reload();
   }

Without specifying the path you can do:

constructor(private route: ActivatedRoute, private router: Router) { }

reload() {
  this.router.routeReuseStrategy.shouldReuseRoute = () => false;
  this.router.onSameUrlNavigation = 'reload';
  this.router.navigate(['./'], { relativeTo: this.route });
}

And if you use query params you can do:

reload() {
  ...
  this.router.navigate(['./'], { relativeTo: this.route, queryParamsHandling: 'preserve' });
}

import { DOCUMENT } from '@angular/common';
import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-refresh-banner-notification',
  templateUrl: './refresh-banner-notification.component.html',
  styleUrls: ['./refresh-banner-notification.component.scss']
})

export class RefreshBannerNotificationComponent {

  constructor(
    @Inject(DOCUMENT) private _document: Document
  ) {}

  refreshPage() {
    this._document.defaultView.location.reload();
  }
}