Switch up the styling in Angular 2+ depending on the current route

I am currently working on creating a tab menu using Angular (v2.4.5). The active tab is determined by the route.

Here are some example routes:

const routes: Routes = [
  {
    path: 'tab1',
    component: Tab1Component,
  },
  {
    path: 'tab2',
    component: Tab2Component,
  }
];

If a user navigates to http://localhost/tab2, I want the tab2 to be highlighted (change tab CSS).

What would be the most effective way to achieve this?

Answer №1

RouterLinkActive

This feature allows you to include a specific CSS class to an element when the link's route is active.

<a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>

You also have the option to assign the RouterLinkActive instance to a template variable and check the isActive status directly:

<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
  Bob {{ rla.isActive ? '(already open)' : ''}}
</a>

Explore more about RouterLinkActive directive here

Answer №2

To achieve an active state on your navigation links, simply use routerLinkActive="active" in your code like shown below:

<nav>
      <a routerLink="/page1" routerLinkActive="active">Page 1</a>
      <a routerLink="/page2" routerLinkActive="active">Page 2</a>
</nav>

To style the active link in CSS, define the active class for your nav links as follows:

nav {
   color: black;
}
nav .active {
   color: blue;
}

For more information about routes, visit this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing angular-material-design into an Angular 4 application with the help of Angular CLI

Is there a proper way to use bootstrap-material-design in an Angular 4 app with Angular CLI? In my project, I included the css file in my styles.css like this: @import "~bootstrap-material-design/dist/css/bootstrap-material-design.min.css"; Although I c ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

Using Express.js to serve simple SVG files (Technique involving Cheerio.js)

My goal is to manipulate SVGs before sending them through Express.js. The code snippet I am using is as follows: app.get("/iconic/styles/:style/:base/:icon", function (req, res) { var style = req.params.style; var base = req.params.base; var i ...

Custom CSS Editor for Third Party Visual Studio Themes

Are there any reliable and user-friendly style sheet editors that can be integrated with Visual Studio? I recently came across a resource editor that surpassed the default version for opening .resx files. This got me thinking, there may be some advanced ...

The error message "Type 'void' does not match the expected type 'ObservableInput'" is triggered by ngrx effects

@Injectable() export class ApiSearchEffects { @Effect() search$: Observable<any> = this.actions$ .ofType(query.ActionTypes.QUERYSERVER) .debounceTime(300) .map((action: query.QueryServerAction) => action.payload) .switchMa ...

Adding an HTML input element to a span tag does not seem to function as intended in Angular 2

Hey, I'm working on a form that requires users to replace text in a sentence. For example, 'Today is ', where the user will enter the current day. However, I'm facing difficulty injecting inputs using 'innerHTML' alone. Here&a ...

"Customizing the topbar of Twitter Bootstrap for right-to

Attempting to implement twitter bootstrap for a top navigation bar on my master page. http://jsfiddle.net/ZqCah/1/ Encountering some issues and seeking assistance: 1- Desiring to switch the direction of all content to right-to-left (rtl). This would me ...

Close CSS Accordion when Clicked

I have a CSS accordion that I would like to close each panel upon clicking. Can this be accomplished using only CSS, or will JavaScript need to be added? #accordion input:not(:checked) + div { display: none; } #accordion input:checked + div { displ ...

"Take control of FileUpload in PrimeNG by manually invoking it

Is there a way to customize the file upload process using a separate button instead of the component's default Upload button? If so, how can I achieve this in my code? Here is an example of what I've attempted: <button pButton type="button" ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

What steps do I need to take in order to ensure that each webpage displays unique thumbnails?

As a newcomer to website development, I recently looked into implementing open graph on my site. However, I ran into an issue where I could only set one thumbnail for the entire website. This posed a problem as I wanted each navigation menu tab (Home, Abou ...

What is the method to move the h1 tag slightly to the right?

Whenever I use HTML's <h1>Heading Here</h1> tag, the heading appears too close to the left side of the browser window. I would like it to shift slightly towards the right side (not centered though). How can I achieve this adjustment? Can ...

Opacity in IE 8 will impact every child element within

I need to apply opacity to a div element. Here is my current CSS: background: rgb(255, 255, 255); /* Fallback for non-rgba supporting browsers */ background: rgba(255, 255, 255, .7); filter: alpha(opacity=70); /* For IE 7 and older versions */ -ms-filter: ...

Navigation in PHP webpages and determining the active page

In my template.php file, I am including navigation.php from a separate page. My goal is to have the current page highlighted with a specific CSS style as I navigate through different pages on my website. I want the active link to be dynamically styled base ...

Angular-highcharts used to create a stacked bar chart display

const dataArray = [{ name: "LTNS", id: 1, percentage: 60, price: 900000 }, { name: "NPCS", id: 2, percentage: 30, price: 342000 }, { name: "MARCOS", id: 3, percentage: 10, price: 600000 }] To create a stacked ...

Issue with jQuery dialog button visibility in IE7 only appears when hovering over it

I'm currently experiencing some issues with IE7, specifically with my dialog not functioning correctly. Although the dialog itself works fine, the button on it does not display properly until I hover over its intended placement. Below is the jQuery c ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

Using the onclick event in JavaScript to create transition effects for swapping images

I am working on a website where I display 3 images. Instead of redirecting the users to a new page, I want to keep them on the same page. Question: How can I implement a functionality where clicking a <button> will display 3 new images in the view w ...

Why do my navigation bar items in Bootstrap get highlighted in blue and underlined?

<!Doctype html> <html> <head> <meta charset="utf-8"> <title>IBAE-Information Library</title> <link rel="stylesheet" href="/Users/jeevabharathi/Desktop/Project.css"> <script sr ...

Guide on how to access the key of an object within the ngx-bootstrap typeahead feature?

When creating a custom component that utilizes ngx-bootstrap's Typeahead feature, the documentation indicates the ability to specify which item of an object can be searched for. If I have a list of key-value objects, how can I search for the value and ...