Aasif
Aasif

Reputation: 13

How to add active navigation based on URL in angular?

Here is my problem-- I have created a navbar with RouterLink directive and I wanted my navigation link to be active to the current URL path so I am using RouterLinkActive directive. But my CSS active class is not updating to any URL path. I don't know why. Is there any solution to this problem ?

Here is my code

Navigation bar: app.component.html

<nav class="header-links">
      <img src="../assets/images/logo.png" alt="" class="logo">
      <a routerLink="/contact" routerLinkActive="active" style="margin-right: 35px;">Contact us</a>
      <a routerLink="/product" routerLinkActive="active">Our Product</a>
      <a routerLink="/about" routerLinkActive="active">About us</a>
      <a routerLink="/home" routerLinkActive="active">Home</a> 
</nav>

CSS to be apply : app.component.css

.active {
    color: black;
    text-decoration: underline;
}

Routing Paths: app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './component/about/about.component';
import { ContactComponent } from './component/contact/contact.component';
import { HomeComponent } from './component/home/home.component';
import { ProductComponent } from './component/product/product.component';

const routes: Routes = [
  {path:'', redirectTo:'home', pathMatch:'full'},
  {path:'home', component: HomeComponent},
  {path:'about', component: AboutComponent},
  {path:'product', component: ProductComponent},
  {path:'contact', component: ContactComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { relativeLinkResolution: 'legacy' })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I tried [routerLinkActiveOptions]="{exact: true}" still nothing changes and also I tried to set my active css class to be global still nothing. Am I missing anything here ?

Upvotes: 0

Views: 2322

Answers (1)

Aasif
Aasif

Reputation: 13

Since no response I found myself an answer by using parent class to navigate to the active class

.header-links .active {
    color: black;
    text-decoration: underline;
 }

Posting this answer, If it might helps anyone in the future.

Upvotes: 1

Related Questions