Search code examples
angular5angular-routerangular-animations

Angular 5: Route animations for navigating to the same route, but different parameters


In my Angular 5 application, the user may navigate to a route which uses the same route, but with different parameters. For example, they may navigate from /page/1 to /page/2.

I want this navigation to trigger the routing animation, but it doesn't. How can I cause a router animation to happen between these two routes?

(I already understand that unlike most route changes, this navigation does not destroy and create a new PageComponent. It doesn't matter to me whether or not the solution changes this behavior.)

Here's a minimal app that reproduces my issue.


Solution

  • This is an old question but that's it if you're still searching. Add this code to your app.Component.ts file.

    import { Router, NavigationEnd } from '@angular/router';
    
    constructor(private _Router: Router) { }
    
    ngOnInit() {
      this._Router.routeReuseStrategy.shouldReuseRoute = function(){
      return false;
      };
      this._Router.events.subscribe((evt) => {
        if (evt instanceof NavigationEnd) {
            this._Router.navigated = false;
            window.scrollTo(0, 0);
        }
      });
    }
    

    By using this code the page is going to refresh if you clicked on the same route no matter what is the parameter you added to the route.

    I hope that helps.

    Update

    As angular 6 is released with core updates you don't need this punch of code anymore just add the following parameter to your routs import.

    onSameUrlNavigation: 'reload'
    

    This option value set to 'ignore' by default.

    Example

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

    Stay up to date and happy coding.