Having issues with Angular Material, specifically with mat-list-item and routerLinkActive not functioning as expected

Currently, I am working with a navigation view that utilizes the MatSidenavModule. The issue I am encountering is on mobile screens. When I click a mat-list-item, the mat-sidenav closes as expected. However, upon opening the mat-sidenav again, Material always marks the first item in the list as active. Interestingly, if I use a div, it functions properly (displaying in red). The problem arises when using mat-list-item. I am unsure of what mistake I may be making. Any help would be appreciated. Thanks!

<mat-sidenav-container [hasBackdrop]="false">

    <mat-sidenav 
        #sidenav [mode]="windowInnerWidth > 1200 ? 'side' : 'push'" 
        [opened]="windowInnerWidth > 1200 ? true : false" 
        >
        <div class="mat-typography">
            <h2>Material</h2>
        </div>
        <mat-divider></mat-divider>
        <mat-nav-list>

            <!-- it does not work -->
            <mat-list-item 
                *ngFor="let menuItem of menuItems"
                [routerLink]="[menuItem.path]"
                routerLinkActive="router-active"
                (click)="windowInnerWidth < 1200 ? sidenav.close() : null">
                <span matListItemTitle>{{menuItem.title}}</span>
            </mat-list-item>

            <!-- it works -->
            <div *ngFor="let menuItem of menuItems"
                [routerLink]="[menuItem.path]"
                routerLinkActive="router-active"
                (click)="windowInnerWidth < 1200 ? sidenav.close() : null">
                {{menuItem.title}}
            </div>
        </mat-nav-list>
    </mat-sidenav>

    <mat-sidenav-content>
        <app-toolbar [windowInnerWidth]="windowInnerWidth" (toggleEvent)="toggleSidenav()"></app-toolbar>
        <div class="router-outlet-container">
            <router-outlet></router-outlet>
        </div>     
    </mat-sidenav-content>
  
</mat-sidenav-container>
.router-active {
    color: red;
}

Answer №1

Here is my solution to the problem, I hope it can assist someone:

.menu-link {
    display: block;
    width: 100%;
    height: 100%;
    text-decoration: none;
    color: inherit;
    padding: 20px 0px;
}

mat-list-item.router-active {
    background-color: rgba(0, 0, 0, 0.1);
}
<mat-list-item *ngFor="let menuItem of menuItems" (click)="windowInnerWidth < 1200 ? sidenav.close() : null" routerLinkActive="router-active">
  <mat-icon matListItemIcon *ngIf="menuItem.icon" class="menu-item-icon">{{menuItem.icon}}</mat-icon>
  <a class="menu-link" [routerLink]="[menuItem.path]">
    <span matLine>{{menuItem.title}}</span>
  </a>
</mat-list-item>

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

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

Customizing error messages to display validation errors instead of default text errors in the Django UserCreationForm

I'm encountering an issue with the registration form on my website. The form itself is straightforward, but I'm facing a problem where if a username is already taken or if the two password fields don't match, Django doesn't respond afte ...

Trouble with z-index | initial div out of four malfunctioning

Currently, I am attempting to practice by replicating the design shown in this image: However, I have encountered an issue that has been persisting for some time: I'm struggling to understand why this issue is occurring. An interesting observation i ...

What sets apart Import { module } from lib and import module from lib/module in JavaScript?

I'm currently working on optimizing my vendor bundle.js file, which has gotten quite large due to my use of the material-ui library. import Card from 'material-ui'; // This is not ideal as it imports everything Could someone please explai ...

Error message: Angular 2 JsonpModule import not defined

Within my app.module.ts file, I have the specified code import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {JsonpModule} from '@angular/http'; import {AppComponent} from & ...

Fixing the 401 (Unauthorized) error when attempting to log in

I keep encountering a 401 error when trying to log in with JWT authentication. Strangely, the signup page works perfectly fine and successfully adds the user to the database. However, for some reason, the login functionality is not working. I'm unsure ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

Retrieving header information in Angular 6

I am currently working on an example that I found on this website, but I seem to be facing an error that I can't figure out. Even after carefully reviewing my code, I'm still unable to pinpoint the mistake. Specifically, when I use "response => ...

Dealing with promises in ng-if function in AngularJS

When working with AngularJS, I have a scenario where I am using ng-show="isChecked('ID')" in an element to access a $rootScope array that is generated in another controller. Here's my function: $scope.isChecked = function(ID) { c ...

Efficiently communicating updates to clients after executing multiple HTTP requests simultaneously in RxJS

Objective: Execute multiple asynchronous HTTP requests simultaneously with RxJS and trigger a callback after each request is completed. For instance: fetchData() { Observable.forkJoin( this.http.get('/somethingOne.json').map((res:Re ...

How to remove an event listener that was added within a function in JavaScript?

I am encountering an issue while trying to remove an event listener that was created inside a function. Oddly enough, it works perfectly when I move the event listener outside of the function. See the example below: <body> <div id='myDiv&apo ...

Unable to invoke Angular function from within jQuery

I am currently using the angular full calendar plugin and have successfully added a context menu in the event render function. The context menu is functioning properly, but I am facing an issue where I want to call an Angular function when a context menu i ...

We apologize, but Google Pay encountered an unexpected developer error that caused the request to fail. Please try again later

When attempting to make a payment using Google Pay on a real device in the TEST environment, I am encountering the error mentioned in the title. I have followed the guidance provided in the Google docs and tried converting 'gateway' to a string, ...

Utilizing a TypeScript definition file (.d.ts) for typings in JavaScript code does not provide alerts for errors regarding primitive types

In my JavaScript component, I have a simple exporting statement: ./component/index.js : export const t = 'string value'; This component also has a TypeScript definition file: ./component/index.d.ts : export const t: number; A very basic Typ ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

Tips for maintaining the footer at the bottom of the page regardless of the screen size

In my current project, I am dealing with several web pages. For each page, I have arranged three div tags: Header Body (content) Footer The issue arises when it comes to the body div tag, which houses the main content of a page such as forms and descrip ...

Having trouble retrieving Firebase data to display on a React chart

I am currently utilizing ApexChartJs in my React project. However, when attempting to retrieve dynamic data from my Firebase database, it returns undefined. https://i.stack.imgur.com/8lcnz.png Below is a snippet of code from my project: import React, { u ...

Experiencing challenges with showcasing numerical values in the grid cells

My latest project involves creating an interactive sudoku solver. I've successfully created a grid made up of various elements to resemble an empty sudoku grid. However, my challenge lies in getting the numbers to display within the grid cells. Click ...

JavaScript truthy values referring to numbers

According to the rules outlined below: Falsy: false 0 (zero) '' or "" (empty string) null undefinded NaN (e.g. the result of 1/0) Truthy: Anything else I'm puzzled as to why, in the tests that follow, only the number 1 is considered "tr ...

What are some reasons why the XMLHttpRequest ProgressEvent.lengthComputable property could return a value of

I've been struggling to implement an upload progress bar using the XMLHttpRequest level 2 support for progress events in HTML5. Most examples I come across show adding an event listener to the progress event like this: req.addEventListener("progress ...