Reloading Same Component by routerLink to Same Route in Angular
I would like to merge some of the information from some answers here into a single answer.
You can achieve reloading the same component from the same route by:
- Changing configuration in
app-routing.module.ts
- Providing a
RouteReuseStrategy
(which returns false
) in the component defining routerLink
(s)
Example:
app-routing.module.ts
//...
@NgModule({
// See https://angular.io/api/router/Router#properties
imports: [RouterModule.forRoot(routes, {
// onSameUrlNavigation: 'ignore', // default behavior
onSameUrlNavigation: 'reload'
})],
exports: [RouterModule],
})
export class AppRoutingModule {}
links.component.ts
(arbitrary name, yours will be different)
export class LinksComponent implements OnInit {
// ...
constructor(
// ...
private router: Router) { }
ngOnInit(): void {
// ...
// With the below line you can now reload the same component from the same route
this.router.routeReuseStrategy.shouldReuseRoute = () => { return false; };
}
}
Supporting Docs
How to handle a navigation request to the current URL. One of:
- 'ignore' : The router ignores the request.
- 'reload' : The router reloads the URL. Use to implement a "refresh" feature.
Note that this only configures whether the Route reprocesses the URL and triggers related action and events like redirects, guards, and resolvers. By default, the router re-uses a component instance when it re-navigates to the same component type without visiting a different component first. This behavior is configured by the RouteReuseStrategy. In order to reload routed components on same url navigation, you need to set onSameUrlNavigation to 'reload' and provide a RouteReuseStrategy which returns false for shouldReuseRoute.
Considerations:
- In our usage we only used static URLs; we haven't tested with dynamic URLs in our approach.
- This example was tested using Angular 12.