I would like to create a navigation in an Angular application where I can access the same page from multiple "parent" page and keep the navigation aware of the page it's coming from.
I'm using the routerLinkActive="active"
on my navigation. I have two pages (Favorites, All users) that display a list of users. Users have a details page that you can navigate to using users/userId
.
What I'd like to do is that when the user details link is clicked from the "Favorites" list, the "active" navigation stays on the "Favorites" menu button, and when I click from All users it stays on All users
This is how my routes are currently configured
const routes: Routes = [
{
path: 'favorites',
component: FavoritesComponent
},
{
path: 'all',
component: AllUsersComponent
},
{
path: 'user/:id',
component: UserDetailComponent,
}
This is how my routes are currently configured and, obviously, when I navigate to the user/id
page, neither favorites
nor all
is "active" in my navigation bar.
You can reuse the same component as a child route under each main route, i.e favorites
and all
. The key thing here is to define an empty route path that goes to the main component for that route and then create a detail route that will fall under the main route. Your route config should look something like this:
const appRoutes: Routes = [
{
path: 'favorites',
children: [
{
path: '',
component: FavoritesComponent
},
{
path: 'user/:id',
component: UserDetailComponent,
}
]
},
{
path: 'all',
children: [
{
path: '',
component: AllUsersComponent
},
{
path: 'user/:id',
component: UserDetailComponent,
}
]
},
{
path: 'user/:id',
component: UserDetailComponent,
},
{ path: '**', redirectTo: "/all" }
];
With the above configuration the favorites
and the all
links will behave as you want.