Angular 5 Material - 如何将mat-nav-list锚链接设置为在单击时处于活动状态

Kay*_*Kay 6 angular-material angular

如何在我的实现中将锚链接设置为活动状态.

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

.TS

goToChat(conversation) {
    this.router.navigate(['main/chat/', conversation._id]);
}
Run Code Online (Sandbox Code Playgroud)

.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
            }
        ]
    },
];
Run Code Online (Sandbox Code Playgroud)

上面的代码循环用户对话并创建他们正在聊天的用户列表.每个列表项都是指向页面右侧聊天组件的链接.当用户单击链接并且我希望将其设置为活动时.

LuJ*_*aks 11

通过添加routerLinkActive指令将锚设置为"活动"类:

<mat-nav-list>
    <a mat-list-item routerLinkActive="active">{{link.title}}</a>
</mat-nav-list>
Run Code Online (Sandbox Code Playgroud)

问题是在Angular Material包中显然没有为活动状态定义样式:

角材料/ SRC/LIB /列表/ _list-theme.scss

角材料/ SRC/LIB /列表/ list.scss

所以必须定义一个活动样式:

.mat-nav-list a.active {
    background: blue;
}
Run Code Online (Sandbox Code Playgroud)


mou*_*nds 8

routerLinkActive是一个属性,routerLink因此它只能与routerLink绑定一起使用。

要将活动链接设置routerLink为路由路径的样式,并设置routerLinkActive为您自己的类,您将使用它来指示“活动”。

例如:

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

现在使用 css 定位链接:

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


小智 -6

尝试使用类似的东西:

<a [routerLink]="['main/chat/',conversation._id]">{{getOtherUsers(conversation)}}</a>
Run Code Online (Sandbox Code Playgroud)

有关它的更多信息,请访问https://angular.io/guide/router#router-links