How to highlight selected mat-list-item with color in angular?

Viewed 35885

Here I have multiple mat-list-item when i click on notification or Dashboard or comments i want to highlight it with red color how its possible in angular?

<mat-list>
   <mat-list-item style="cursor: pointer" routerLink="/base/dashboard">Dashboard</mat-list-item>
   <mat-list-item style="cursor: pointer" routerLink="/base/notification">Notification</mat-list-item>
   <mat-list-item style="cursor: pointer" routerLink="/base/comments">Comments</mat-list-item>
</mat-list>
5 Answers

Since you're using routerLink already, you should take advantage of routerLinkActive

html:

<mat-list>
   <mat-list-item style="cursor: pointer" routerLink="/base/dashboard" [routerLinkActive]="['is-active']">Dashboard</mat-list-item>
   <mat-list-item style="cursor: pointer" routerLink="/base/notification" [routerLinkActive]="['is-active']">Notification</mat-list-item>
   <mat-list-item style="cursor: pointer" routerLink="/base/comments" [routerLinkActive]="['is-active']">Comments</mat-list-item>
</mat-list>

css:

.is-active {
    background-color: red;
}

I think like so

clickedItem: 'dashboard' | 'notification' | 'comments';


onClick(item: 'dashboard' | 'notification' | 'comments') {
  this.clickedItem = item;
}
.red {
  background-color: red;
}
<mat-list>
   <mat-list-item [ngClass]="{red: clickedItem === 'dashboard'}"            (click)="onClick('dashboard')" style="cursor: pointer" routerLink="/base/dashboard">Dashboard</mat-list-item>
   <mat-list-item [ngClass]="{red: clickedItem === 'notification'}"  (click)="onClick('notification')" style="cursor: pointer" routerLink="/base/notification">Notification</mat-list-item>
   <mat-list-item  [ngClass]="{red: clickedItem === 'comments'}" (click)="onClick('comments')" style="cursor: pointer" routerLink="/base/comments">Comments</mat-list-item>
</mat-list>

We can achieve this by below style changes

.mat-nav-list .mat-list-item:focus,
.mat-action-list .mat-list-item:focus,
.mat-list-option:focus {
  background: #76b900 !important;
}

When the list-items navigate somewhere, <mat-nav-list> should be used with <a mat-list-item> elements as the list items. The nav-list will be rendered using role="navigation" and can be given an aria-label to give context on the set of navigation options presented. Additional interactive content, such as buttons, should not be added inside the anchors.

<mat-nav-list>
    <a mat-list-item 
    *ngFor="let report of category.reports">
    <span>{{ report.reportName }}</span>
    </a>
</mat-nav-list>

This Can be Used if you want to specifically target and change color. For hovering effects the above one should work fine

.mat-list-item {
background-color: #fefefe; 
}

A different approach is to use the aria-selected attribute of the mat-list-option element

.mat-list-option[aria-selected="true"] {
  background: #76b900 !important;
}
Related