如何用角颜色突出显示所选的垫列表项?

DDD*_*DDD 5 angular-material angular

当我单击通知或仪表板或注释时,我想使用红色突出显示它,这时我有多个mat-list-item。

<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>
Run Code Online (Sandbox Code Playgroud)

Pet*_*Kim 7

由于您已经在使用routerLink,因此应该利用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>
Run Code Online (Sandbox Code Playgroud)

CSS:

.is-active {
    background-color: red;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我是这样想的

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


onClick(item: 'dashboard' | 'notification' | 'comments') {
  this.clickedItem = item;
}
Run Code Online (Sandbox Code Playgroud)
.red {
  background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)