I have a problem with routerLinkActive in angular 4. I have this setup.
export const FruitRoutes = [
{
path: 'fruits/:id', component: FruiteNav,
children: [
{path: '', component: FruitGeneral},
{path: 'settings', component: FruitSettings}
]
}
];
It's a tab page for a single fruit. Ex: fruits/4 (general tab) and fruits/4/settings (settings tab)
The tab navigator (FruitNav) is set up like following and it works in most of the cases:
<ul class="nav nav-tabs">
<li class="nav-item">
<a [routerLink]="['/fruits', fruitId]" class="nav-link" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">General</a>
</li>
<li class="nav-item">
<a [routerLink]="['/fruits', fruitId,'settings']" class="nav-link" routerLinkActive="active">Settings</a>
</li>
</ul>
<router-outlet></router-outlet>
Now the si problem: The route is currently at fruits/4. If I am within any of the child tabs or even in main nav class, and call for another fruitId, the routerLinkActive won't work. Ex:
<a style="color:#fff" [routerLink]="['/fruits', 5,'settings']" class="nav-link">Test</a>
will navigate to fruit/5 but none of the tabs will be active/selected
A typical usecase could be a list of similar fruits that the user could navigate to.
Does anyone have a solution for this?
I figured it out. My route configuration was not correctly setup. The 'parent' route should redirect to my 'default tab' route, like this:
export const FruitRoutes = [
{
path: 'fruits/:id', component: FruiteNav,
children: [
{path:'',redirectTo: 'general',pathMatch: 'full'},
{path: 'general', component: FruitGeneral},
{path: 'settings', component: FruitSettings}
]
}
];
Then I changed the routerLink for the general tab link to:
<ul class="nav nav-tabs">
<li class="nav-item">
<a [routerLink]="['/fruits', fruitId,'general']" class="nav-link" routerLinkActive="active">General</a>
</li>
<li class="nav-item">
<a [routerLink]="['/fruits', fruitId,'settings']" class="nav-link" routerLinkActive="active">Settings</a>
</li>
</ul>
<router-outlet></router-outlet>
Tada! it works!