Angular 5 Material - How to set mat-nav-list anchor link to be active on click

Viewed 40249

How do i set anchor links to be active in my implementation.

.html

<mat-nav-list class="conversation-list">
    <mat-list-item *ngFor="let conversation of conversations">
        <a (click)="goToChat(conversation)">{{getOtherUsers(conversation)}}</a>
    </mat-list-item>
</mat-nav-list>

<div class="chat-box">
    <router-outlet></router-outlet>
</div>

.ts

goToChat(conversation) {
    this.router.navigate(['main/chat/', conversation._id]);
}

.routing.module.ts

import { ChatComponent } from './chat.component';
import { ChatDetailComponent } from './chat-detail/chat-detail.component';

const CHAT_ROUTES = [
    {
        path: '',
        component: ChatComponent,
        children: [
            {
                path: ':id',
                component: ChatDetailComponent
            }
        ]
    },
];

The above code loops over a users conversation and creates a list of users they are chatting with. Each list item is a link to a chat component on the right of the page. When user clicks a link and i want it to be set to active.

5 Answers

The anchor is set to have the class "active" by adding routerLinkActive directive:

<mat-nav-list>
    <a mat-list-item routerLinkActive="active">{{link.title}}</a>
</mat-nav-list>

The problem is there is apparently no styles defined for an active state in the Angular Material package:

angular-material/src/lib/list/_list-theme.scss

angular-material/src/lib/list/list.scss

so an active style has to be defined:

.mat-nav-list a.active {
    background: blue;
}

You are able to use the .mat-list-item-focus class to focus the list item:

<mat-nav-list>
  <mat-list-item class="mat-list-item-focus">Focused List Item</mat-list-item>
  <mat-list-item>Not Focused List Item</mat-list-item>
</mat-nav-list>

<mat-nav-list routerLinkActive="active current" [routerLinkActiveOptions]="{exact:true}"> Bo'lim bookYangi kitoblar booksEng ko'p o'qilgan bookBadiiy kitoblar booksTarixiy kitoblar bookFantastik bookjahon adabiyoti bookMaktab darsliklari bookmashhurlar hayoti <a mat-list-item routerLinkActive="active current" *ngIf="isAdmin" routerLink="user">UFoydalanuvchilar

Related