Javascript 在 Angular 中,您如何确定活动路线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34323480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:09:49  来源:igfitidea点击:

In Angular, how do you determine the active route?

javascripttypescriptangularangular2-routing

提问by Michael Oryl

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 therouter 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 团队更改其路由器,有效的方法发生了多次变化。最终将成为Angular 中路由器的 Router 3.0 版本打破了许多这些解决方案,但提供了一个非常简单的解决方案。从 RC.3 开始,首选解决方案是使用本答案中[routerLinkActive]所示的方法。

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?

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

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.

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

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.

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

回答by jessepinho

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

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

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

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

有关详细信息,请参阅文档不足的routerLinkActive指令。(我主要是通过反复试验来解决这个问题的。)

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

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

回答by Alex Santos

I've replied this in another question but I believe it might be relevant to this one as well. Here's a link to the original answer: Angular 2: How to determine active route with parameters?

我已经在另一个问题中回答了这个问题,但我相信它也可能与这个问题有关。这是原始答案的链接: Angular 2: How to determine active route with parameters?

I've been trying to set the activeclass without having to know exactly what's the current location (using the route name). The is the best solution I have got to so far is using the function isRouteActiveavailable in the Routerclass.

我一直在尝试设置活动类,而不必确切知道当前位置(使用路线名称)。到目前为止,我得到的最好的解决方案是使用类中可用的函数isRouteActiveRouter

router.isRouteActive(instruction): Booleantakes one parameter which is a route Instructionobject and returns trueor falsewhether that instruction holds true or not for the current route. You can generate a route Instructionby using Router's generate(linkParams: Array). LinkParams follows the exact same format as a value passed into a routerLinkdirective (e.g. router.isRouteActive(router.generate(['/User', { user: user.id }]))).

router.isRouteActive(instruction): Boolean接受一个参数,它是一个路由Instruction对象,并返回truefalse该指令是否适用于当前路由。您可以Instruction使用Routergenerate(linkParams: Array)生成路由。LinkParams 遵循与传递给routerLink指令(例如router.isRouteActive(router.generate(['/User', { user: user.id }])))的值完全相同的格式。

This is how the RouteConfigcould look like (I've tweaked it a bit to show the usage of params):

这就是RouteConfig 的样子(我稍微调整了一下以显示参数的用法)

@RouteConfig([
  { path: '/', component: HomePage, name: 'Home' },
  { path: '/signin', component: SignInPage, name: 'SignIn' },
  { path: '/profile/:username/feed', component: FeedPage, name: 'ProfileFeed' },
])

And the Viewwould look like this:

是这样的:

<li [class.active]="router.isRouteActive(router.generate(['/Home']))">
   <a [routerLink]="['/Home']">Home</a>
</li>
<li [class.active]="router.isRouteActive(router.generate(['/SignIn']))">
   <a [routerLink]="['/SignIn']">Sign In</a>
</li>
<li [class.active]="router.isRouteActive(router.generate(['/ProfileFeed', { username: user.username }]))">
    <a [routerLink]="['/ProfileFeed', { username: user.username }]">Feed</a>
</li>

This has been my preferred solution for the problem so far, it might be helpful for you as well.

到目前为止,这是我对这个问题的首选解决方案,它可能对您也有帮助。

回答by Quy Tang

I solved a problem I encountered in this linkand I find out that there is a simple solution for your question. You could use router-link-activeinstead in your styles.

我解决了我在这个链接中遇到的一个问题,我发现你的问题有一个简单的解决方案。您可以router-link-active在您的样式中使用。

@Component({
   styles: [`.router-link-active { background-color: red; }`]
})
export class NavComponent {
}

回答by tomaszbak

Small improvement to @alex-correia-santos answer based on https://github.com/angular/angular/pull/6407#issuecomment-190179875

对基于https://github.com/angular/angular/pull/6407#issuecomment-190179875 的@alex-correia-santos 答案的小改进

import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
// ...
export class App {
  constructor(private router: Router) {
  }

  // ...

  isActive(instruction: any[]): boolean {
    return this.router.isRouteActive(this.router.generate(instruction));
  }
} 

And use it like this:

并像这样使用它:

<ul class="nav navbar-nav">
    <li [class.active]="isActive(['Home'])">
        <a [routerLink]="['Home']">Home</a>
    </li>
    <li [class.active]="isActive(['About'])">
        <a [routerLink]="['About']">About</a>
    </li>
</ul>

回答by Jason Teplitz

You can check the current route by injecting the Locationobject into your controller and checking the path(), like so:

您可以通过将Location对象注入控制器并检查来检查当前路线path(),如下所示:

class MyController {
    constructor(private location:Location) {}

    ...  location.path(); ...
}

You will have to make sure to import it first:

您必须确保先导入它:

import {Location} from "angular2/router";

You can then use a regular expression to match against the path that's returned to see which route is active. Note that the Locationclass returns a normalized path regardless of which LocationStrategyyou're using. So even if you're using the HashLocationStragegythe paths returned will still be of the form /foo/barnot#/foo/bar

然后,您可以使用正则表达式匹配返回的路径以查看哪个路由处于活动状态。请注意,Location无论LocationStrategy您使用的是哪种路径,该类都会返回规范化的路径。因此,即使您使用的HashLocationStragegy是返回的路径,它的形式仍然/foo/bar不是#/foo/bar

回答by Ankit Singh

how do you determine what the currently active route is?

您如何确定当前活动的路线是什么?

UPDATE: updated as per Angular2.4.x

更新:根据 Angular2.4.x 更新

constructor(route: ActivatedRoute) {
   route.snapshot.params; // active route's params

   route.snapshot.data; // active route's resolved data

   route.snapshot.component; // active route's component

   route.snapshot.queryParams // The query parameters shared by all the routes
}

see more...

查看更多...

回答by Günter Z?chbauer

To mark active routes routerLinkActivecan be used

routerLinkActive可以使用标记活动路线

<a [routerLink]="/user" routerLinkActive="some class list">User</a>

This also works on other elements like

这也适用于其他元素,如

<div routerLinkActive="some class list">
  <a [routerLink]="/user">User</a>
</div>

If partial matchesshould also be marked use

如果部分匹配也应标记使用

routerLinkActive="some class list" [routerLinkActiveOptions]="{ exact: false }"

As far as I know exact: falseis going to be the default in RC.4

据我所知exact: false将成为 RC.4 中的默认值

回答by Artem Zinoviev

Right now i'm using rc.4 with bootstrap 4 and this one works perfect for me:

现在我正在使用 rc.4 和 bootstrap 4,这个对我来说很完美:

 <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">
    <a class="nav-link" [routerLink]="['']">Home</a>
</li>

This will work for url : /home

这将适用于 url :/home

回答by Zze

Just thought I would add in an example which doesn't use any typescript:

只是想我会添加一个不使用任何打字稿的例子:

<input type="hidden" [routerLink]="'home'" routerLinkActive #home="routerLinkActive" />
<section *ngIf="home.isActive"></section>

The routerLinkActivevariable is bound to a template variable and then re-used as required. Unfortunately the only caveat is that you can't have this all on the <section>element as #homeneeds to be resolved priorto the parser hitting <section>.

routerLinkActive变量绑定到模板变量,然后根据需要重新使用。不幸的是,唯一需要注意的是,您不能将所有这些都放在<section>元素上,因为#home需要在解析器点击之前解决<section>

回答by Ivan

Below is the method using RouteData to style menuBar items depending of the current route:

下面是使用 RouteData 根据当前路由设置 menuBar 项目样式的方法:

RouteConfig includes data with tab (current route):

RouteConfig 包含带有选项卡的数据(当前路由):

@RouteConfig([
  {
    path: '/home',    name: 'Home',    component: HomeComponent,
    data: {activeTab: 'home'},  useAsDefault: true
  }, {
    path: '/jobs',    name: 'Jobs',    data: {activeTab: 'jobs'},
    component: JobsComponent
  }
])

A piece of layout:

一块布局:

  <li role="presentation" [ngClass]="{active: isActive('home')}">
    <a [routerLink]="['Home']">Home</a>
  </li>
  <li role="presentation" [ngClass]="{active: isActive('jobs')}">
    <a [routerLink]="['Jobs']">Jobs</a>
  </li>

Class:

班级:

export class MainMenuComponent {
  router: Router;

  constructor(data: Router) {
    this.router = data;
  }

  isActive(tab): boolean {
    if (this.router.currentInstruction && this.router.currentInstruction.component.routeData) {
      return tab == this.router.currentInstruction.component.routeData.data['activeTab'];
    }
    return false;
  }
}