Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload component in angular 2 when router link clicked

Tags:

angular

I have an angular 2 rc6 app, the app uses the angular 2 router to load components into the router outlet. This all works fine generally, but my problem is that when a user clicks on a link [routerLink] for a page they are already routed to, then they are expecting the component to reload.

Reloading a component does not seem to be the default behaviour for the angular 2 router, instead it seems to recognise the component is already the current one and do nothing, does anyone know how to change this?

like image 336
Slicc Avatar asked Sep 05 '16 20:09

Slicc


2 Answers

I just bumped into the same problem and couldn't find a suitable solution. Also, everybody's best friend, Google, didn't help much. In my case, I needed a general-purpose active form reset behavior, and reloading the current component seemed a pretty good approach. Of course, reset form buttons are far better, but I've seen that lots of users are tempted to reloading the page (by clicking the same link multiple times).

I managed to trick the Router into reloading the component on each routerLink click, with the following code in the AppComponent:

constructer(private router: Router) {
  // override the route reuse strategy
  this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };

  this.router.events.subscribe((evt) => {
    if (evt instanceof NavigationEnd) {
      // trick the Router into believing it's last link wasn't previously loaded
      this.router.navigated = false;
      // if you need to scroll back to top, here is the right place
      window.scrollTo(0, 0);
    }
  });
}
like image 124
Mihail Cuculici Avatar answered Nov 04 '22 10:11

Mihail Cuculici


For me 3 steps were helping to fix that.

  1. "trick the Router" as Mihail Cuculici said (added in app-component)
  2. Adding runGuardsAndResolvers: "always" to routing module
  3. Not sure why it fails but when I tried to fetch all of the data in the resolver constructor and just return the data in the resolve function it worked only the first time I loaded the component, so I moved it all the resolve function.
like image 1
Tomer Halaf Avatar answered Nov 04 '22 09:11

Tomer Halaf