7
votes

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?

3
Can you share any code? - Tomas Schier
To be honest there is not really a whole lot of code to share here, you just need a link with a [routerLink] attribute, and then click on it twice, the first time the component is loaded, the second time nothing happens. - Slicc

3 Answers

3
votes

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);
    }
  });
}
0
votes

This is currently not supported. https://github.com/angular/angular/issues/9811 It was mentioned somewhere that there are plans to add more control about reuse of routed components later (after final).

Usually you re-initialize like

constructor(route:ActivatedRoute) {
  route.params.subscribe(params => initAfterRouteChange(params));
}

If this doesn't work because the DOM needs to be reinitialized (for example because of some non-Angular2 library that updates the DOM. You can use *ngIf to purge the DOM of the component and re-add it.

0
votes

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.