andyrue
andyrue

Reputation: 952

How to change to route with same component without page reload

Angular 4.3.1

I have routes that look like this:

{ path: ':department', loadChildren: 'app/pages/pages.module#PagesModule' }

And pagesRoutes

{
  path: '',
  component: PagesComponent,
  pathMatch: 'full',
},
{
  path: ':id',
  component: PagesComponent,
}

Say I navigate to /department-name. The PagesComponent is loaded and I do a lookup to find the default page for the department and load the content. If I then navigate to /department-name/1, the PagesComponent is being initialized again and the screen reloads, I'd like to find a way to not have it reload between those two route changes. At this point, if I navigate to /department-name/2 the content changes without the page reloading like I want. Is there a way I can reorganize things so I don't experience a component reload when navigating between /department-name and /department-name/id?

I found this hack which I don't think can work since :department is a dynamically generated route. Unless there is a way for me to get that param inside the router config?

There is also this SO write-up that uses RouteReuseStrategy, but it uses a static array of possible routes to reuse. I could possibly do this if I can build that array from an HTTP call. I guess I could do that at initial app load?

Any better suggestions? Thanks for looking.

Upvotes: 2

Views: 3658

Answers (1)

Abhay
Abhay

Reputation: 6760

 // First import in your component:    
import { Router, NavigationEnd } from '@/router';

 // Then in your component class constructor use below code: 

constructor(private router: Router) { 
    this.router.routeReuseStrategy.shouldReuseRoute = function(){
      return false;
    };
    this.router.events.subscribe((evt) => {
        if (evt instanceof NavigationEnd) {
            this.router.navigated = false;
        }
    });
  }

 // Finally in any of your method, where you want to refresh use below code
  for refresh
 any_method_name() {
    this.router.navigate(['/']);
 }

** NO Hack or something, its official solution for loading component without refresh. **

Upvotes: 2

Related Questions