user1250264
user1250264

Reputation: 905

Want to click on same route to refresh the page but not triggering anything

I am working on an Angular v12 app with navigation menus that has working routes to each components. I have 1 page I need to have the ability to click on the menu and refresh the page. If I am on User page and the User nav menu has already been clicked, I like to click it again and route back to itself to refresh the page with default data. Right now, When I click on the nav menu, nothing happens. I placed breakpoints in my NAV component and it does not break if I click on the route again.

Any help/guidance is greatly appreciated.

My routes are configured in the app-routing.module.ts

const appRoutes: Routes = [
  {path: "", component: HomeComponent},
  {path: "users", loadChildren: ()=> UsersModule},
]

In my Nav Component ts file, I look at the router state but

export class MyNavComponent implements OnInit {

  @Input() menuItems: any[] = [];
 
  selectedMenu = {} as RouteInfo;

  constructor(private router: Router) { 
 
    router.events.subscribe((event) => {

      if(event instanceof NavigationStart) {

// I placed a breakpoint here and it does not break if same menu link is clicked on again.
      
      }
    });

  }

  ngOnInit(): void {
  }
  
}

Upvotes: 1

Views: 2897

Answers (1)

Luke Gatchell
Luke Gatchell

Reputation: 81

Sounds like you may want the onSameUrlNavigation configuration option.


class CustomReuseStrategy implements RouteReuseStrategy {
  shouldReuseRoute() {
    return false;
  }
}

const ROUTES: Routes = [
  ...
];

@ngModule({
  imports: [
    RouterModule.forRoot(ROUTES, { onSameUrlNavigation: 'reload' }),
  ],
  providers: [
    {
      provide: RouteReuseStrategy,
      useClass: CustomReuseStrategy,
    },
  ],
  exports: [RouterModule],
})

Note that this only configures whether the Route reprocesses the URL and triggers related action and events like redirects, guards, and resolvers. By default, the router re-uses a component instance when it re-navigates to the same component type without visiting a different component first. This behavior is configured by the RouteReuseStrategy. In order to reload routed components on same url navigation, you need to set onSameUrlNavigation to 'reload' and provide a RouteReuseStrategy which returns false for shouldReuseRoute.

Upvotes: 1

Related Questions