How to reload current page?
This is the most simple solution if you just need to refresh the entire page
refreshPage() {
window.location.reload();
}
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 shouldReuseRoute
because 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;
};