I am working on an Angular project. I'm struggling with refresh action in a component.
I would like to refresh the router's components on button click.
I have refresh button when I click on it the component/router need to be refresh.
I tried window.location.reload()
and location.reload()
these two are not suitable for my need. Please help if anyone aware of it.
-
Can you share your code in this question ? what you are tried.– ChandruDec 14, 2017 at 13:07
-
it's a complex code, it has N number of line of code, difficult to share– Sreehari BallampalliDec 14, 2017 at 13:14
-
@Saurabh, normally it's not necesary reload a component. You can have a function (e.g. call "restart") and call the function in your button Refresh. If you need subscribe to change path, or another service, use the function ngOnInit -your component must extends OnInit-, not the constructor– EliseoDec 14, 2017 at 20:17
-
This is what I did with Angular 9 stackoverflow.com/a/60909777/1072395– WladaMar 29, 2020 at 3:24
22 Answers
After some research and modifying my code as below, the script worked for me. I just added the condition:
this.router.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this.router.navigate(['Your actualComponent']);
});
-
2I'm using this in an injectable service. I replaced
"your actualComponent"
with a variable. The variable is set is set tothis.location.path()
before the call tonavigateByUrl
. That way, no need to pass any parameters from calling component or duplicate/pass around routes.– TewrJan 9, 2019 at 13:48 -
9can you please explain what is 'RefrshComponent' and 'Your actualComponent'? Jan 13, 2019 at 15:59
-
25Most everyone will be fine using
'/'
where/RefrshComponent
is, and for[Your actualComponent"]
you would just pass the url (and/or params) that you would like to reload such asthis.router.navigate(["/items"])
. This hack essentially redirects to the top URL, and then very quickly back to the intended URL which is unnoticeable to most users and appears to be the most elegant hack to achieve this simply.– soflyFeb 1, 2019 at 23:04 -
5I agree this should definitely work... but it fails in my app (Angular 6). If I use
'/'
as my dummy route it goes (viaredirectTo
) to where my app-routing.module.ts redirects to on a path of''
(empty string) and stops, not proceeding to the completion route in thenavigate()
call. If I use a non-existent string (e.g./foo
) as my dummy route, it goes (viaredirectTo
) to where my app-routing.module.ts redirects for**
(everything else) and again stops, not going to the real route. Curiously, the URL bar DOES change to the real route. Any thoughts on what is different here? May 10, 2019 at 3:08 -
1this can cause an infinite redirection loop if not used carefully Jul 28, 2019 at 11:49
Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!
DeleteEmployee(id:number)
{
this.employeeService.deleteEmployee(id)
.subscribe(
(data) =>{
console.log(data);
this.ngOnInit();
}),
err => {
console.log("Error");
}
}
-
13While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.– hellowNov 2, 2018 at 7:44
-
9Agreed, this only works if you want to refresh the component from within the component - if you are dealing with child/external components this.ngOnInit() will not work May 14, 2019 at 3:20
-
7Even though it works for component, it doesn't reset form validators. Jul 16, 2019 at 8:08
-
5Works perfect, thank you. And regarding the explanation AFAIC, the code says it all. Mar 11, 2020 at 10:42
-
6ngOnInit is a lifecycle method called by angular. you shouldn't call it yourself. if there's some logic from ngOnInit that you want to execute again, just move it into a method and call that method.– LarryPMar 14, 2022 at 7:49
Adding this to code to the required component's constructor worked for me.
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();
}
}
Refer to this thread for more details - https://github.com/angular/angular/issues/13831
Fortunately, if you are using Angular 5.1+, you do not need to implement a hack anymore as native support has been added. You just need to set onSameUrlNavigation to 'reload' in the RouterModule options :
@ngModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})],
exports: [RouterModule],
})
More information can be found here: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
-
You can use
router.onSameUrlNavigation = 'reload'
property of injected Router, too.– 0zkr PMDec 12, 2018 at 3:23 -
6Using angular 6, to me this made no difference, that is, component did not reload. The accepted answer works however.– TewrJan 9, 2019 at 13:42
-
7Although not entirely clear in the docs,
onSameUrlNavigation
is intended to reinvoke Guards/Resolvers, and not to reload already routed components. See github.com/angular/angular/issues/21115 for more on this. This solution will work for larger more complex applications using Guards/Resolvers but will fail for simple examples.– soflyFeb 1, 2019 at 23:07 -
2yes, onSameUrlNavigation will fire the navigation events again, but this does not reload the component Sep 27, 2019 at 19:54
-
yes! this solution is working. May be you could mention more detail in you answer. Jun 16, 2021 at 6:15
this is little bit out of box and I dont know whether this helps you or not but have yo tried
this.ngOnInit();
its a function so whatever code you have in it will be recalled just like a refresh.
One more way without explicit route:
async reload(url: string): Promise<boolean> {
await this.router.navigateByUrl('.', { skipLocationChange: true });
return this.router.navigateByUrl(url);
}
-
1
-
2Actually it gives Error: Cannot match any routes. URL Segment: '.' if you don't have the route in the application routes– sgabbFeb 1, 2021 at 14:50
calling ngOnInit()
does not work for my complicated component, I end up using this
reloadCurrentRoute() {
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
-
1Simple and efficient. All other answers did not yield desired behavior, especially when using a child component requiring a reload of the parent component too. Aug 4, 2022 at 12:37
Just follow the below steps:
- add
{onSameUrlNavigation: 'reload'}
as below in your app-routing.modules.ts
@NgModule({
imports: [ RouterModule.forRoot(routes,{onSameUrlNavigation: 'reload'})],
exports: [ RouterModule ]
})
- add
this.router.routeReuseStrategy.shouldReuseRoute = () => false
as below in you component ts file constructor:
constructor(private router: Router) { this.router.routeReuseStrategy.shouldReuseRoute = () => false; }
- Now click the button and call ajax server call, get the desired data from server and replace your global variable in TS file with new data.
- call
this.router.navigate([/sameRoute]);
in the last. replace sameRoute with your route url. - make sure to return false at the end in your refresh button's onClick method, otherwise it will lead to main routing page instead of same page reload.
These steps will reload your page. :)
For more details: https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2
I am using Angular 12.
-
1This is the correct answer for me thanks god. You can change 4 with this.router.navigateByUrl(this.router.url); Jan 17, 2022 at 12:43
-
Amazing! This is the only solution that worked for me! I'm using Angular 13 Nov 3, 2022 at 5:15
This can be achieved via a hack, Navigate to some sample component and then navigate to the component that you want to reload.
this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);
-
SampleComponent means it should be an empty component or another component in my project? Dec 14, 2017 at 13:10
-
1
-
-
if I give true I am getting an error message : [ts] Type 'true' has no properties in common with type 'NavigationExtras' Dec 14, 2017 at 13:54
-
@SreehariBallampalli check the updated answer, you need to pass an object { skipLocationChange: true } Dec 14, 2017 at 16:12
There are problems with some of the answers before:
- one should not call lifecycle methods such as ngOnInit() directly.
- re-navigating to some URL is a sub-optimal solution, especially if the component you are dynamically loading is only a small part of a big page
This worked for me (I don't know if it is recommendable or optimal)
- In the component to be dynamically loaded, add a public reference to the ChangeDetectorRef.
- I assume that the dynamically loaded data has some input data, ("tags" in the example), which is updated after the fact and is creating rendering problems.
@Input()
tags: string[] = [];
constructor(public changeDetector: ChangeDetectorRef )
- In the parent component doing the dynamic loading, after having created the child component dynamically and maybe set some data to it, call the created instance's changeDetector.markForCheck() as follows:
constructor(private vcrf: ViewContainerRef, private cfr: ComponentFactoryResolver, private elementRef: ElementRef) {
}
public loadComponent(): void {
const componentFactory = this.cfr.resolveComponentFactory(TagsListComponent);
const component = this.container.createComponent(componentFactory);
component.instance.tags = /* whatever data we want to pass */;
component.instance.changeDetector.markForCheck();
...
loadComponent() is a custom function that could be called, for example, once the parent page scrolls to some position in the parent component, indicating that the dynamic component should be shown.
In my application i have component and all data is coming from API which i am calling in Component's constructor. There is button by which i am updating my page data. on button click i have save data in back end and refresh data. So to reload/refresh the component - as per my requirement - is only to refresh the data. if this is also your requirement then use the same code written in constructor of component.
Just change the routeReuseStrategy
from the angular Router:
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
Set the routerproperty "navigated" to false:
this._router.navigated = false;
Then navigate to your component:
this._router.navigate(['routeToYourComponent'])
After that reinstate the old/default routeReuseStrategy:
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
You can also make a service out of this:
@Injectable({
providedIn: 'root'
})
export class RouterService {
constructor(
private _activatedRoute: ActivatedRoute,
private _router: Router
) { }
reuseRoutes(reuse: boolean) {
if (!reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
if (reuse) {
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
async refreshPage(url?: string) {
this._router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
this._router.navigated = false;
url ? await this._router.navigate([url]) : await this._router.navigate([], { relativeTo: this._activatedRoute });
this._router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
};
}
}
kdo
// reload page hack methode
push(uri: string) {
this.location.replaceState(uri) // force replace and no show change
await this.router.navigate([uri, { "refresh": (new Date).getTime() }]);
this.location.replaceState(uri) // replace
}
constructor(private router:Router, private route:ActivatedRoute ) {
}
onReload(){
this.router.navigate(['/servers'],{relativeTo:this.route})
}
just do this : (for angular 9)
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
constructor(@Inject(DOCUMENT) private document: Document){ }
someMethode(){ this.document.location.reload(); }
-
7Please read the OPs comment, refreshing the whole page is not an option for him, it defeats the purpose of having angular in the first place– ihor.ethMay 4, 2020 at 16:43
-
1
html file
<a (click)= "getcoursedetails(obj.Id)" routerLinkActive="active" class="btn btn-danger">Read more...</a>
ts file
getcoursedetails(id)
{
this._route.navigateByUrl('/RefreshComponent', { skipLocationChange: true }).then(() => {
this._route.navigate(["course",id]);
});
router.navigate['/path']
will only takes you to the specified path
use router.navigateByUrl('/path')
it reloads the whole page
In my case I needed to reload specific routes (not all in the application), so adding the global setting {onSameUrlNavigation: 'reload'}
had no effect, while this.router.routeReuseStrategy.shouldReuseRoute = () => false
in the component works but modifies the global settings of the router.
The solution was to save the original router configuration to a variable before changing it in the component's constructor as indicated @abhishek-singh by the first answer of the problem.
private routeReuseStrategy:any;
constructor(
private router:Router
) {
this.routeReuseStrategy = this.router.routeReuseStrategy.shouldReuseRoute;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
And when exiting the path, remap the original configuration using the OnDestroy hook.
public ngOnDestroy():void
{
this.router.routeReuseStrategy.shouldReuseRoute = this.routeReuseStrategy;
}
private saveRouterStrategyReuseLogic: any;
ngOnInit() {
// Save logic
this.saveRouterStrategyReuseLogic = this.router.routeReuseStrategy.shouldReuseRoute;
this.router.routeReuseStrategy.shouldReuseRoute = (future, curr) => { return false; };
}
ngOnDestroy() {
this.router.routeReuseStrategy.shouldReuseRoute =
this.saveRouterStrategyReuseLogic;
}
Other way to refresh (hard way) a page in angular 2 like this
it's look like f5
import { Location } from '@angular/common';
constructor(private location: Location) {}
pageRefresh() {
location.reload();
}
-
1He said that reloading the whole page isn't suitable, this reloads the whole page, not just a single/multiple components. Jul 2, 2018 at 19:10
-
I ended up using this, except the angular location service doesn't have a reload, so I used window. Sep 30, 2019 at 17:48