RouterLinkActive用于带有参数的RouterLink(/动态) [英] RouterLinkActive for RouterLink with parameters (/dynamic)

查看:90
本文介绍了RouterLinkActive用于带有参数的RouterLink(/动态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览应用程序本身时使用动态生成的链接时,RouterLinkActive不起作用.

RouterLinkActive is not working when using a dynamically generated link when navigating through the app itself.

例如在我的顶部导航中,我有这个;

e.g. in my top navigation i have this;

<a [routerLink]=['user', currentUser.name] routerLinkActive='active'>{{currentUser.name}}</a>

虽然可以使用硬编码版本.

Whilst the hardcoded version would work.

<a [routerLink]=['user','bob']>View Bobs Account</a>

这是一大笔钱; https://plnkr.co/edit/BYKMucE3Y75uJSpV5VWx?p=preview

单击"John"和"Dynamic Router Link Name ="和"John"都应处于活动状态.有时这可以在第一次单击时起作用,如果是这样,则单击回到主页",再单击约翰",即使href相同,您也只会看到硬编码链接被注册为活动.

Click on "John" and "Dynamic Router Link Name = " and "John" should both be active. This sometimes work on the first click, if so, then click back to "Home", the click again on "John", you'll see only the hardcoded link is registered as active, even though the hrefs are identical.

这是设计/不可能的吗?还是我设置不正确?

Is this designed/impossible? or am i setting something incorrectly?

推荐答案

在您的组件中:

import {Router} from '@angular/router';

isActive(instruction: any[]): boolean {
  // Set the second parameter to true if you want to require an exact match.
  return this.router.isActive(this.router.createUrlTree(instruction), false);
}

在您的HTML中:

<a [class.active]="isActive(['user', currentUser.name])">

Router.isActive()文档在angular.io

Router.isActive() documentation on angular.io

这篇关于RouterLinkActive用于带有参数的RouterLink(/动态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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