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

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

问题描述

注意:这里有许多不同的答案,大多数都曾经有效.事实是,随着 Angular 团队更改其路由器,有效的方法发生了多次变化.最终将成为 Angular 中路由器的路由器 3.0 版本打破了许多这些解决方案,但提供了一个非常简单的解决方案.从 RC.3 开始,首选的解决方案是使用 [routerLinkActive]this answer.

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>

如果只需要一个类,或者更简单的格式:

Or an even simpler format if only one class is needed:

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

请参阅记录code>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天全站免登陆