在Angular中,您如何确定活动路线? [英] In Angular, how do you determine the active route?

查看:123
本文介绍了在Angular中,您如何确定活动路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意: 这里有许多不同的答案,大多数答案都是有效的。事实是,当Angular团队改变其路由器时,有效的改变了很多次。最终将成为Angular中 路由器的Router 3.0版本打破了许多这些解决方案,但它提供了一个非常简单的解决方案。从RC.3开始,首选解决方案是使用 [routerLinkActive] ,如这个答案

NOTE: There are many different answers here, and most have been valid at one time or another. The fact is that what works has changed a number of times as the Angular team has changed its Router. The Router 3.0 version that will eventually be the router in Angular breaks many of these solutions, but offers a very simple solution of its own. As of RC.3, the preferred solution is to use [routerLinkActive] as shown in this answer.

在Angular应用程序中(当我写这篇文章时,目前在2.0.0-beta.0版本中),如何你确定当前活动路线是什么?

In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?

我正在使用一个使用Bootstrap 4的应用程序,我需要一种方法将导航链接/按钮标记为活动时他们的相关组件显示在< router-output> 标签中。

I'm working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <router-output> tag.

我意识到我可以维护当我点击其中一个按钮时,我自己就会看到状态,但这并不包括多条路径进入同一路线的情况(例如主导航菜单以及主要组件中的本地菜单)。

I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn't cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).

任何建议或链接都​​将不胜感激。谢谢。

Any suggestions or links would be appreciated. Thanks.

推荐答案

使用新的 Angular路由器,您可以为所有链接添加 [routerLinkActive] =['your-class-name']属性:

With the new Angular router, you can add a [routerLinkActive]="['your-class-name']" attribute to all your links:

<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>

如果只需要一个类,则为简化的非数组格式:

Or the simplified non-array format if only one class is needed:

<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>

参见记录不足 routerLinkActive 指令了解更多信息。 (我通常通过反复试验来解决这个问题。)

See the poorly documented routerLinkActive directive for more info. (I mostly figured this out via trial-and-error.)

更新: routerLinkActive 指令的更好文档现在可以在这里找到。 (感谢@Victor Hugo Arango A.在下面的评论中。)

UPDATE: Better documentation for the routerLinkActive directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)

这篇关于在Angular中,您如何确定活动路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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