Angular: 如何通过参数判断活跃路由?

Angular: How to determine active route with parameters?

我已经阅读了 ,但我仍然不清楚如何使用参数确定活动路由?

现在我是这样做的:

<a [routerLink]="['/Profile/Feed', {username: username}]"
   [ngClass]="{active: getLinkStyle('/profile/john_doe/feed')}">
   Feed for {{username}}
</a>

在我的组件中:

getLinkStyle(path:string):boolean {
  console.log(this._location.path()); // logs: '/profile/john_doe/feed'
  return this._location.path() === path;
}

这会起作用,因为我将用户名作为字符串传递。有没有办法通过传递正确的参数来做到这一点??

我一直在尝试设置 active class 而不必确切知道当前位置 (使用路线名称)。这是迄今为止我得到的最佳解决方案。

这就是 RouteConfig 的样子 (我稍微调整了一下使其看起来像您想要的)

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

View 看起来像这样:

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

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

只需检查 auto-defined router-link-active class 到 a 元素。

在Angular 2 rc1 router.isRouteActive中不存在了。 我在任何地方都找不到可行的解决方案,但我能够像这样解决它(自定义方法 isActiveRoute 可以解决问题):

App.component.ts:

import { Component } from '@angular/core';
import { Routes, Route, Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router';
import { HomeComponent } from './home.component';
import { P1Component } from './p1.component';

@Component({
    selector: 'app',
    templateUrl: './app/app.template.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([
    { path: '/', component: HomeComponent },
    { path: '/p1', component: P1Component }
])

export class AppComponent implements OnInit {

    constructor(public router: Router){ }

    isActiveRoute(route: string) {
        return this.router.serializeUrl(this.router.urlTree) == this.router.serializeUrl((this.router.createUrlTree([route])));
    } 
}

App.template.html:

            <ul class="nav navbar-nav">
                <li [class.active]="isActiveRoute('/')">
                    <a class="nav-link" [routerLink]="['/']">Home</a>
                </li>
                <li [class.active]="isActiveRoute('/p1')">
                    <a class="nav-link" [routerLink]="['/p1']">Page 1</a>
                </li>

您可以使用 Angular2 公共包中的新定位服务:https://angular.io/docs/js/latest/api/router/Location-class.html#!#path-anchor

import { Location } from '@angular/common';

...

export class YourClass {
    constructor(private _loc:Location) {}

    getCurrentPath() {
        return this._loc.path();
    }
}

Note: it's better to use Router service to trigger route changes. Use Location only if you need to interact with or create normalized URLs outside of routing.

请注意: 文档说从 router 导入,但我拥有的最新 betta 版本在 common 中有 Location 服务。

使用即将推出的新 Angular 2 路由器(在我撰写本文时位于 version 3.0-alpha.7),这非常简单。

您需要做的就是在 link 中使用 [routerLinkActive] 指令。

<a [routerLinkActive]="['active']" [routerLink]="['/contact',  contact.id ]">
    {{contact.name}}
</a>

当 Angular 2 正式发布且不再是候选版本时,您将使用它。我现在正在使用路由器的 alpha,没有任何问题。

Here's Plunk demonstrating it。您可以看到 link 在您单击它们时变红。这是将 active class 分配给它们的指令。当然,您可以使用您选择的任何 class 名称。

对于 Angular 版本 4+,确定模板中的活动路由相当容易,因为有一个用于此目的的内置指令名称 routerLinkActive,您可以使用以下方式:

      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/home">Home</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/about-us">About Us</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a title="Contact Us" class="nav-link " routerLink="/contact-us">Contact</a>
      </li>
    </ul>

试试这个:

<li   class="ann_profileimg" [routerLinkActive]="['active']" [routerLink]="['profile']">
            <div class="ann_header_menu_left ann_profile_avatar_small"></div>
            <span>Vishnu </span>
          </li>
<a [routerLink]="['/Profile/Feed', {username: username}]"
routerLinkActive="active-item" [routerLinkActiveOptions]="{exact: false}">
   Feed for {{username}}
</a>

active-item 是您要为活动菜单提供的 css class。 routerLinkActive 用于为活动菜单提供 css,其中 routerLinkActiveOptions 将告诉您是否希望 url 完全匹配。这通常有助于创建和编辑相同的 url(使用参数)

示例:

用于创建:

http://localhost/feed

待编辑:

http://localhost/feed/1