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

Traverse a collection of nested objects containing arrays as their values

Consider the following object: { "apples": [ "one", "two" ], "oranges": [ "three", "four" ] } If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below? for (var ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...

What is the best way to apply a consistent set of values when altering fields conditionally in dynamically generated fields within Angular?

I just finished developing a dynamic row that consists of 2 dropdowns and a text field. Users have the ability to add or remove additional rows as needed. There is a specific condition in place: if the first dropdown value is 'Date' and the seco ...

The website displays perfectly in Atom, however, it is not functional in any web browser

My website is currently in the development phase, and I'm experiencing issues with certain div elements not positioning correctly once the site goes live. Specifically, the "Follow Us" tab at the bottom of the site, among other divs, has been affecte ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Utilize PHP to transform JSON data into JavaScript

Hello, I am a newcomer to Stackoverflow and I need some assistance. My issue involves converting JSON with PHP to JavaScript. I am using PHP to fetch data from a database and create JSON, which I then want to convert for use in JavaScript as an object (obj ...

How can JavaScript nested AJAX requests and promises be properly chained together?

I'm currently facing a dilemma when it comes to setting the correct order of execution for the tasks at hand. Let's say I need to initiate an AJAX call, then handle the data and store it in IndexedDB using the idb-keyval library, which operates o ...

Generate a collection of div elements as child nodes

I'm working on a project where I have multiple rows with input fields. My goal is to create an array for each row that contains the values of the inputs. For example, if I have 3 rows and the values of 'input1' are 1, 'input2' are ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...

The dimensions of the div element are adjusting as I scroll on Firefox Mobile, however, there is a way to prevent this from happening using Angular

I've been conducting tests on my Angular application on various mobile devices. While everything seems to function properly on Chrome and Safari, an issue arises when it comes to Firefox: during scrolling, the browser's toolbar and URL bar appear ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Angular: A guide to exporting a service from an npm module

I have a useful service within my Angular 2 package that I am looking to publish on NPM. Here are the key lines of code for this service: public showModal: Subject<any> = new Subject<any>(); public $showModal = this.showModal.asObservable(); ...

Capybara with Angular Material Select

Is it possible to use select in RoR RSpec + Capybara? I typically use: select 'something', from: 'select_name' However, this method does not work for Angular's md-select. Capybara displays the following error message: Capybara:: ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

Issue encountered when attempting to install React modules

Attempted to install sass-loader, as well as node-sass using both yarn and npm; however, encountered identical errors. Various methods were tried: yarn add <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="057664767628696a646160 ...

Res.write inexpressively proceeding without waiting for the completion of an array of promises

snippet const processAll = async (tasks) => { let processes = []; tasks.forEach(task => { if (task === "1") processes.push(asyncProcess1); if (task === "2") processes.push(asyncProcess2); if (task === "3&q ...

What is the best way to achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

Attempting to collapse the offcanvas menu in React Bootstrap by clicking on a link

Currently, I am utilizing a mix of React Bootstrap and React to develop a single-page application. In an attempt to make the Offcanvas menu close when clicking a link, I have experimented with various approaches. One method involved creating an inline scri ...

Create a dynamic select2 field based on the value selected in another dropdown menu

Starting with an initial dropdown where a value needs to be selected: <select id="indexID" name="indexID" class="form-control" onChange="updateSector();" style="width:300px;"> <option value='' selected>Choose an Index</option> ...