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

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

问题描述

在浏览应用程序本身时使用动态生成的链接时,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>

这里有一个 plunk;https://plnkr.co/edit/BYKMucE3Y75uJSpV5VWx?p=preview

A plunk for this is here; https://plnkr.co/edit/BYKMucE3Y75uJSpV5VWx?p=preview

点击John",Dynamic Router Link Name ="和John"应该都处于活动状态.这有时在第一次点击时起作用,如果是这样,然后点击返回主页",再次点击约翰",您将看到只有硬编码链接被注册为活动链接,即使 hrefs 是相同的.

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 中:

In your HTML:

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

Router.isActive() angular.io 文档

Router.isActive() documentation on angular.io

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

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