angularangular-router

Angular router reuse strategy - use same component on two routes


I need to use same component on two different routes, and I am reusing both routes. I am following this example:

example

The component has a text field. I am navigating to first route and enter some text into that field. Then I switch to another route, but what I see is the same text I just entered. I thought the router runs two instances of the same class; thus, I should be able to enter different texts into the routes. Any idea?

Thanks


Solution

  • The instances are unique per the routing path, plus there was a typo in the routerLink both point to compA maybe that caused the issue, below I changed both routes to same component and it maintains the state per route (url path).

    const routes: Routes = [
      {
        path: 'compA',
        component: ComponentA,
      },
      {
        path: 'compB',
        component: ComponentA,
      },
    ];
    

    Stackblitz Demo