Angular5,为RouterLink设置活动类 [英] Angular5, setting active class for RouterLink

查看:44
本文介绍了Angular5,为RouterLink设置活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过给它提供类来更改当前选择的routerLink与其他类,以改变某些样式.

I am trying to distinguish currently selected routerLink from others by giving it class which will change some styles.

因此在html中,我向链接添加了一些属性和事件.

So in html i added some properties and event to links.

app.component.html:

app.component.html:

<nav class="nav-list">
  <a routerLink="/dashboard" 
     class="nav-link" 
     [class.activePage]="pageSelected === 'dashboard'" 
     (click)="setActivePage('dashborad')" >
     Dashboard</a>
  <a routerLink="/products" 
     class="nav-link" 
     [class.activePage]="pageSelected === 'products'" 
     (click)="setActivePage('products')" >
  Products List</a>
</nav>

在打字稿中,我实现了变量和方法.

and in typescript I have implemented variable and method.

app.component.ts:

app.component.ts:

import { Component } from '@angular/core';


@Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] }) 
  export class AppComponent {

  pageSelected:string;

  setActivepage(page){
    this.pageSelected = page;   }

}

但是,尽管已经在样式中设置了activePage类,但是单击链接后没有任何反应.

but there is nothing happening after link click although activePage class is already set in styles.

有人知道如何使其工作吗?

Somebody got an idea how to make it work ?

推荐答案

@vikas和@Mertcan Diken已经向您展示了解决方案!我向您展示了如何使用它.

@vikas and @Mertcan Diken already showed you the solution! I show you how you should use it.

角形"路由器知道哪个路由处于活动状态,并将在活动的 a 标记上为您设置一个类.您只需要定义应该设置的类即可.

The 'angular' router knows which route is active and will set a class on the active a tag for you. You only have to define which class should be set.

.css

.active-route {
    background: black;
    border-bottom: 2px solid red;      
}

.html

<nav class="nav-list">
    <a routerLink="/dashboard" routerLinkActive="active-route" class="nav-link" >Dashboard</a>
    <a routerLink="/products" routerLinkActive="active-route" class="nav-link">Products List</a>
</nav>

这篇关于Angular5,为RouterLink设置活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆