Angular Material <mat-sidenav> Applies Class to Inner Element Instead of Top-Level Navigation

Discussão em 'Angular' iniciado por Dilshan Prasad, Fevereiro 20, 2025.

  1. I'm using Angular Material's <mat-sidenav> in my Angular application, and I need to dynamically apply a collapsed class when the sidebar is minimized.

    Problem: Even though there is only one <mat-sidenav> in my template, when I inspect the DOM in Chrome DevTools, I notice that multiple levels of <mat-sidenav> exist in the rendered code (likely due to Angular Material wrapping it internally).

    As a result, my ngClass="{'collapsed': isCollapsed}" is applied only to an inner <mat-sidenav>, but not the top-level element where I need it.

    Current Code:

    Template:

    <mat-sidenav
    *ngIf="data$ | async as items"
    #sidenav
    class="sidebar"
    mode="side"
    opened="true"
    [ngClass]="{ 'collapsed': isCollapsed }"
    (mouseenter)="onMouseEnter()"
    (mouseleave)="onMouseLeave()"
    >
    <div class="sidebar-header">
    <section>
    <mat-icon class="toggle-icon" (click)="isCollapsed = !isCollapsed">
    {{ isCollapsed ? 'chevron_right' : 'chevron_left' }}
    </mat-icon>
    </section>
    </div>

    <mat-nav-list>
    <ng-container *ngFor="let item of items">
    <mat-list-item class="nav-item" *ngIf="item.type === 'LEAF'">
    <a class="nav-link" [routerLink]="item.link">{{ item.label }}</a>
    </mat-list-item>
    </ng-container>
    </mat-nav-list>
    </mat-sidenav>


    Component.ts

    export class SidebarComponent {
    isCollapsed = false;
    }


    What I Tried:

    1. Applying [ngClass] to → It only applies to an inner nested <mat-sidenav>, not the top-level navigation.
    2. Inspecting Chrome DevTools → I see extra div wrappers around <mat-sidenav>, which are injected by Angular Material internally.
    3. Applying ngClass to <mat-sidenav-container> → It doesn't seem to affect the actual <mat-sidenav>.

    Expected Behavior: I want the collapsed class to be applied to the top-level <mat-sidenav>, so that I can properly collapse and style it.

    How can I ensure that the collapsed class is applied to the topmost <mat-sidenav>, instead of only affecting an inner instance?

    Continue reading...

Compartilhe esta Página