Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 309
Kay Avatar asked Nov 20 '17 12:11

Kay


3 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;
}
like image 88
LuJaks Avatar answered Oct 16 '22 09:10

LuJaks


routerLinkActive is a property of routerLink so it can only be used alongside the routerLink binding.

To style an active link set routerLink to the route's path, and set routerLinkActive to your own class you will use to indicate 'active'.

For example:

<a [routerLink]=`main/chat/'${conversation._id}` 
    routerLinkActive="active-link">{{getOtherUsers(conversation)}}</a>

Now use css to target the link:

.active-link {
    background-color: grey;
}
like image 32
mounds Avatar answered Oct 16 '22 09:10

mounds


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>
like image 20
Michael Wilson Avatar answered Oct 16 '22 09:10

Michael Wilson