Search code examples
angularangular-route-segment

How to refresh the parent route and it's components when it is clicked again in Angular?


I have a Master-Detail container component with 2 presentational components master and detail. The user will click the link http://localhost:4200/master. The master component will retrieve the data from the server and display a list of items, and also navigate the detail component to the first item in the list. The route will now change to http://localhost:4200/master/detail:1.

Now the user can go back to and click the link http://localhost:4200/master again. But nothing happens to the master component and no new data is downloaded. The components behave like they are cached.

I want to refresh the whole Master-Detail if the user clicks http://localhost:4200/master again. The data need to be downloaded from the server and display the detail item like the user has clicked the first time.

What settings I need to have in the components or the module, and the changes needed to the routes to make it happen?

This is my current routes:

const detailRoutes = [
  {
    path: 'detail/:id',
    component: DetailComponent
  }
];

const routes: Routes = [
{
  path: 'master',
  component: MasterComponent,
  children: [
    ...detailRoutes
  ],
},
...detailRoutes];

Solution

  • Easiest fix would be to set router option called onSameUrlNavigation to 'reload'

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

    This will force reload when you hit the same URL just as if you navigated to the route for the first time.

    EDIT: in order for ngOnInit to run on same url navigation, you also need to set your router's reuse strategy accordingly.

    Inject your router (app.component preferred):

    import { Router } from '@angular/router';
    
    constructor(private router: Router) {
        this.router.routeReuseStrategy.shouldReuseRoute = () => false;
    }