Search code examples
angularangular-routing

How to route navigation in Angular to the same page and reload


Summary

I am trying to set up navigation to the same component that dynamically loads different content, and can't get that to load properly.

Details

I have a simple application with a route set up in app.module.ts:

const routes: Routes = [
  {path: 'posts/:slug', component: PostComponent}
];

and a router import declaration of:

RouterModule.forRoot(routes, { onSameUrlNavigation: "reload"}),

I added the "reload" from reading the documentation. In PostComponent I set the slug to a property in OnInit():

ngOnInit(): void {
  this.slug = this.route.snapshot.paramMap.get('slug') as string;
}

And when I declare this on my post.component.html:

{{ slug }}
<a routerLink="/posts/through-a-router-link">Through A Router Link</a>

It correctly loads the page the first time, however when I click on the link, it updates my URL to localhost:4200/posts/through-a-router-link but my content doesn't refresh (i.e. the OnInit() doesn't run).

How do I navigate to the same component with a different slug and force a refresh of the content?


Solution

  • The issue is that you are accessing the slug variable on the snapshot. The snapshot only provides a value which can be found for the first time (see this answer). When you access the paramMap without the snapshot you get an Observable which can be subscribed like this:

    ngOnInit(): void {
        this.route.paramMap.subscribe((paramMap) => {
            this.slug = paramMap.get('slug') as string;
        });
    }
    

    So the this.slug variable will be updated every time when the paramMap is updated with a new value.