Guide on changing the color of the selected item in mat-nav-list within angular 6

Recently diving into Angular 6 and facing an issue with my mat-toolbar integrated with mat-sidenav. Everything seems to be functioning fine, but I'm looking to customize the color for the active item in the side nav menu.

Currently, all items have a plain black background, but I want them to change color when selected from the mat-nav-list. Additionally, my attempts to set dividers between each item have been unsuccessful.

Here's a snippet of my app.component.html:

<mat-sidenav-container class="sidenav-container">

  <mat-sidenav #drawer class="sidenav" fixedInViewport="true" [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
    [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!(isHandset$ | async)" style="background:black"> //current background is black
    <mat-toolbar class="menuBar">Menus</mat-toolbar>
    <mat-nav-list>
      <a class="menuTextColor" mat-list-item href="#">Link 1</a> // want to change the color of the selected item.
      <a class="menuTextColor" mat-list-item href="#">Link 2</a> // want to set divider between each item
      <a class="menuTextColor" mat-list-item href="#">Link 3</a>
    </mat-nav-list>
  </mat-sidenav>

  <mat-sidenav-content>
    <mat-toolbar class="toolbar">
      <button class="menuTextColor" type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()" *ngIf="isHandset$ | async">
        <mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
      </button>
      <span class="toolbarHeading">Demo App</span>
    </mat-toolbar>
    <!-- Add Content Here -->
  </mat-sidenav-content>

</mat-sidenav-container>

If anyone has any insights on how to resolve these issues, please share!

Answer №1

To achieve this functionality using Angular Router, you can utilize the routerLinkActive attribute.

According to the documentation for the RouterLinkActive directive:

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

Description

By employing this directive, you can append a CSS class to an element when the link's route becomes active.

For instance:

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

If the URL matches either /user or /user/bob, the 'active-link' class will be attached to the <a> tag. When the URL changes, the class will be removed.

The code example below illustrates a typical scenario:

<mat-nav-list>
  <a mat-list-item routerLink="/home" routerLinkActive="active-list-item">Home</a>
  <a mat-list-item routerLink="/settings" routerLinkActive="active-list-item">Settings</a>
  <a mat-list-item routerLink="/about" routerLinkActive="active-list-item">About</a>
</mat-nav-list>
.active-list-item {
  color: #3F51B5 !important; /* Note: You could also use a custom theme */
}

A few things to keep in mind:

  • You have the flexibility to modify the class name from active-list-item to any other of your choice.
  • The usage of !important in the second code block indicates that the list item styles take precedence over your customized styles.

Here's a working Stackblitz demo.

Answer №2

If you want to update the color of a specific class in Angular Materials 9.0, you can do so by modifying the following CSS:

a.mat-list-item.active { color: #ccc; }

Answer №3

Just in time to offer my solution! I encountered a similar issue with mat-nav-list and mat-menu, but with some CSS tweaks, I was able to make it work the way I wanted. Give it a try and see if it meets your requirements. Here is the SCSS code snippet:

[class^='mat-list-'] {
  &:hover:active {
    background: rgba(255, 255, 255, 0.04);
  }
  &:focus,
  .mat-list-text {
    background: none !important;
  }
}

[mat-menu-item].is-active,
[mat-list-item].is-active {
  background: hsla(0, 0%, 100%, 0.1) !important;
}

Since I have my own dark theme configured, you may need to adjust the colors to suit your preferences. Simply add routerLinkActive="is-active" and you should be good to go.

Best regards,

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

"What is the best way to specify a type for the src attribute in a tsx file within a

<Image src= { sessionData?.user.image} alt="user" width={100} height={100} />` An issue has been encountered: There is a type error stating that 'string | null | undefined' cannot be assigned to type 'stri ...

Error: The page you are trying to access does not have a valid default export. The provided type is not acceptable

Hello, I am a newcomer to the world of react and NextJS. Currently, I am working on a small project using NextJS 13 where I am attempting to display products stored in a JSON file (which will later be moved to a database). The application runs correctly, ...

After updating my Angular version from 8 to 9, an error has been thrown stating "It is not possible to assign the value 'undefined' to the template variable 'limit'"

Recently, I made updates to my Angular 8 project by switching it to the newest version of Angular 9. In one of the template's div elements, I declared a variable and everything seemed to be functioning correctly without any errors. To avoid initializi ...

Every time I attempt to install a package, I encounter an NPM unmet peer dependency issue

Entering the complex world of NPM for the first time has been quite a challenge. After running create-react-app, the installation process is almost complete except for some warning messages: yarn add v1.17.3 [1/4] Resolving packages... warning react-scri ...

Apollo Client is not properly sending non-server-side rendered requests in conjunction with Next.js

I'm facing a challenge where only server-side requests are being transmitted by the Apollo Client. As far as I know, there should be a client created during initialization in the _app file for non-SSR requests, and another when an SSR request is requi ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Error: TypeORM entity import token is not recognized

Currently, I am facing a peculiar error while transpiling my TypeScript code to JavaScript using TypeORM. The error message that pops up is as follows: (function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, M ...

Leveraging property information for a dropdown field

In my index.tsx file, I am fetching data that I pass to the component FormOne. This allows me to access the data in FormOne using props.data const [data, setData] = useState([]); ... return ( ... <FormOne data={data} /> ); I am looking to ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow: UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.n ...

Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this. The CopySchedulefromSiteComponent contains one fiel ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

Angular: The type '"periodic-background-sync"' cannot be assigned to type 'PermissionName'

I am trying to enable background sync, but I keep encountering an error when I try to enter the code. Why can't it be found? Do I need to update something? This is my code: if ('periodicSync' in worker) { const status = await navigato ...

Steps for calculating the average of several columns within a table using Angular 10

Currently, I have a function that successfully calculates the sum of JSON data in all columns on my tables. However, my attempt to get the average of each column is resulting in NaN or infinity. What could be the issue here? Here is my current implementat ...

Using VueJs and typescript, transform the input image into Base64 format

Welcome to my first question on this platform! I am looking for a way to convert an input file (image) from a form using VueJs 3 and typescript to Base64 in order to "send" it to my backend (java, spring boot) and store it in mongodb as part of a "User" m ...

You cannot use .addCursorFlag() with Mongoose Typescript

Here is my mongoose model that retrieves data from the database using a cursor. The cursor has a timeout of 10 minutes as per the documentation. const cursor = this.importRecordModel.find().cursor() I attempted to add the following code at the end of the ...

In Typescript, if at least one element in an array is not empty, the function should return false without utilizing iterators

My current approach involves receiving a string array and returning false if any of the elements in the array is false. myMethod(attrs: Array<String>) { for (const element of attrs) { if (!element) { return false; } } ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...