How to style the currently active route link in Angular 2 using CSS

I want to add custom CSS styles to active router links:

<a [routerLink]='link'>{{name}}</a>

Here's what I attempted so far (Using the default router-link-active class):

.router-link-active {
color: #000;
font-weight: bold;
}

The styling isn't taking effect, and I'm not sure why.

Answer №1

If you are using Angular 2, there is a convenient built-in attribute called routerLinkActive. You can apply it to any link that uses the [routerLink] directive with the following code:

<a [routerLink]='link' routerLinkActive="router-link-active">{{name}}</a>

This will automatically determine the currently active route and apply your specified CSS class (router-link-active) to it.

It's worth noting that if you are using routerLink on elements other than a tags (such as buttons), the routerLinkActive attribute may not work properly. However, this issue is being addressed in the upcoming release of the router - https://github.com/angular/angular/issues/9755

Answer №2

A brand new feature on the latest router is the "routerLinkActive" directive, which is something that catches your attention.

For example:

<a [routerLink]="/user/bob" routerLinkActive="active-link">Bob</a>

Essentially, when the URL is either '/user' or '/user/bob', the active-link class will be applied to the anchor tag. If there are changes in the URL later on, the class will be removed accordingly."

Answer №3

Based on the information provided, my suggestion would be to consider this approach.

<a [routerLink]='link' [ngClass]="{'router-link-active': routerLink.something === something}">{{name}}</a>

If the condition

routerLink.something === something
, or any other specified expression, is met, the corresponding class and styles will be applied.

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

Customize Embed with Angular Directive

I'm currently attempting to customize an embedded object using Angular Directive, but I am running into difficulties getting the directive to function correctly. Here is the code for the object: <object width="250" height="40"> <param n ...

Is there a way to keep a div element stationary during scrolling without using fixed positioning?

Is there a way to prevent a div from moving when scrolling up or down without using the position:fixed property? When an element is fixed, the scroll bar disappears making it impossible to reach the element by scrolling. div{ position:fixed; top:1 ...

What is the best location to insert CSS in an HTML document?

I tried to customize the CSS on my Blogger blog, but unfortunately, I am unable to access the theme designer. As a result, I attempted to add CSS directly into the code using tags. However, I am having trouble locating the tag within the HTML file. This is ...

Numerous input fields available for AJAX auto-complete functionality and name verification

Currently, I am working on implementing a text box that will search through a mysql database and display auto-completed text below the input field. Additionally, I want to include a visual indicator like a confirmation tick or cross to signify whether the ...

Ways to retain previously entered text in the autocomplete feature

My issue involves using a JavaScript autocomplete widget that displays suggestions as I type, but erases my input when I try to browse the list using the down key. YOUR TEXT HERE serves as a placeholder. While not exactly the same problem, you can view ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

Can a custom type be created in Typescript that permits objects but excludes Errors?

Currently working on resolving an odd scenario with a logger. Essentially, calls like log({ info: 'information' }) function as expected, but log(new Error()) falls short. While no solution is readily available, the goal is to override the log m ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

What is the best way to set a value for a specific column using JavaScript in a RadGrid?

One of my requirements involves having a Radgrid where all rows are always in edit mode. Specifically, I am looking to implement a functionality in one of the columns where after an item is edited, all rows in that column should take on the same value. Her ...

Having trouble establishing a connection with Db2 while using protractor

Encountering an issue when attempting to establish a connection with a remote DB2 database, resulting in the following exception: SQL30081N A communication error has been detected. The communication protocol in use is 'TCP/IP'. The com ...

A guide on dynamically adjusting text size based on viewport width and height in React with TailwindCSS

Utilizing React and Tailwind, I am working towards creating two overlapping rectangles with text. The top rectangle's text should be aligned to the left, while the bottom rectangle's text should be aligned to the right. Regardless of window size ...

What is the best way to obtain and display a PDF file (DocumentViewer) within an Ionic 5 application?

I watched a YouTube tutorial on how to open a PDF viewer. The PDF file is located in the assets folder, which is saved under the app folder. I attempted multiple file paths (let filePath = this.file.applicationDirectory + 'public/assets/';) but s ...

Passing a variable from the server to the client function in Meteor with a delay

When I invoke a server function from the client side, it executes a UNIX command and retrieves the output on the server. However, I face an issue where the result is immediately returned as undefined by Meteor.call because the exec command takes some time ...

problem with arranging photos and captions

When viewing this page in a narrow browser window, an issue arises with how the photo captions are displayed at the bottom of the page. It's evident that the caption extends past the right edge of the photo. My preference would be for the photo and c ...

Managing tabular data in reactive forms in Angular

Currently, I am working on a calendar application where I need to manage three tabs within a form - hours timing, out of office, and holiday tabs. I am facing some challenges in efficiently grouping the form due to having only one form and button for event ...

The transition in Vue Js is only effective when elements are entering, not when they are

Attempting to implement a vue js transition from bottom to top and top to bottom. The transition works smoothly from bottom to top when entering, but there is no transition effect when leaving. Below is the CSS code for the transition: .slide-details-mob ...

When utilizing the Turf.nearPoint() function, it is important to consider the type of point being used. The documentation for Turf.nearestPoint() appears to be inaccurate

I have some code that needs to be transcribed from another system, so unfortunately I can't easily share it here. If I could, I would just post the entire project. Recently, I attempted to integrate into our project but encountered error messages. T ...

Enable clickable elements positioned behind an iframe

I am currently working on integrating a third-party chatbot into my web application using an iframe in ASP.NET MVC. Like with any chatbot, a button is provided to start a chat (located on the right-hand side below the screen). When this button is clicked, ...

Having trouble getting Tailwindcss to work with Next.js - what could be causing the configuration issue?

Why is tailwind not displaying correctly in my next.js project? I'm concerned that there might be a problem with my settings. In the styles folder, I have a file called tailwind.css @tailwind base; /* Write your own custom base styles here */ /* S ...

Tips for accessing values from an array in JavaScript

Is there a way to condense the id and name variables into a single variable? I attempted to use $('#vidyagames').tokenInput([variable]); and also tried inputting a URL, but nothing seemed to work. Instead of id and name, I have a function that re ...