【问题标题】:Angular: How to determine active route with parameters?Angular:如何使用参数确定活动路线?
【发布时间】:2016-04-06 21:45:45
【问题描述】:

我已阅读this question about how to determine the active route,但我仍然不清楚如何使用参数确定活动路线?

现在我正在这样做:

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

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

【问题讨论】:

  • 您可以将 $routingPatams 注入您的控制器并从您的路由中获取参数。
  • 是的,我知道,事实上 username 来自 RouteParams。但是我怎样才能将它从我的 HTML 传递给我的组件呢? @Cyber​​Aleks
  • 我想要做的,类似于:[ngClass]="{active: getLinkStyle('/profile/{{username}}/feed')}",但是这当然行不通..
  • 你可以像 '/profile/'+username+'/feed' 那样做
  • 是的,谢谢@Cyber​​Aleks。试过了,但是我的编辑器没有给它正确的语法颜色..所以没有测试它,愚蠢的哈哈!谢谢!

标签: angular angular2-template angular2-routing


【解决方案1】:

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

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

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

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

Here's Plunk demonstrating it。当您单击它们时,您可以看到链接变为红色。这就是将active 类分配给它们的指令。当然,您可以使用您选择的任何类名。

【讨论】:

  • 哇,现在这么简单!这应该是公认的答案。
【解决方案2】:

只需检查自动定义的 router-link-active 类到 a 元素。

【讨论】:

  • 他们是否在 beta 2 版本中实现了这一点?
  • 如果应用router-link-active类,是否可以自动设置active类?因为大多数 CSS 模板都需要其他类名,我不想修改模板。 @AicoKleinOvink Afaik 它已经存在于最新的 alpha 版本中。
  • 他们是在 2.0.0-alpha.37 (2015-09-09) 上实现的。 github.com/angular/angular/issues/3209
  • 我无法更改默认 css 名称,它是硬编码的。我看到每个 [routerLink] 都存在一个 isRouteActive: boolean 属性,但我无法引用它。
  • 似乎routerLinkActive 指令仅适用于Link Params( /foo/bar ),不适用于Query Params ( /foo;value=bar )
【解决方案3】:

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

【讨论】:

  • 如何调整 isActiveRoute 函数以支持路由参数?
【解决方案4】:

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

这就是 RouteConfig 的样子 (我已经对其进行了一些调整以使其看起来像您想要的那样)

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

视图看起来像这样:

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

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

【讨论】:

  • 这看起来很有希望,明天会调查!!非常感谢!
  • 仍然认为来自很棒的 ui-router 的 ui-sref-active 会很棒..
  • 好的,我尝试了您的解决方案@Alex,但无法正常工作。这是我的代码的实际部分:&lt;a class="main" [routerLink]="['/Profile/Feed', {username: profileUser.username}]" [class.active]="router.isRouteActive(router.generate(['/Profile/Feed', {username: profileUser.username}]))"&gt; &lt;h3&gt;&lt;span class="fa fa-home"&gt;&lt;/span&gt;&lt;/h3&gt; Profiel &lt;/a&gt;
  • 它看起来是正确的,你是否有任何机会出错(如果你是这样的话)?提醒一下,您需要导入Routerimport {ROUTER_DIRECTIVES, Router} from 'angular2/router';
  • 当我console.log(router.generate(['/Profile/Feed', {username: profileUser.username}]) 它返回这个对象:ResolvedInstruction {auxInstruction: Object, component: ComponentInstruction, child: ResolvedInstruction}
【解决方案5】:

您可以使用 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();
    }
}

注意:最好使用Router服务来触发路由变化。采用 仅当您需要与规范化 URL 交互或创建规范化 URL 时才定位 在路由之外。

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

【讨论】:

    【解决方案6】:

    试试这个:

    <li   class="ann_profileimg" [routerLinkActive]="['active']" [routerLink]="['profile']">
                <div class="ann_header_menu_left ann_profile_avatar_small"></div>
                <span>Vishnu </span>
              </li>
    

    【讨论】:

      【解决方案7】:

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

      【讨论】:

        【解决方案8】:
        <a [routerLink]="['/Profile/Feed', {username: username}]"
        routerLinkActive="active-item" [routerLinkActiveOptions]="{exact: false}">
           Feed for {{username}}
        </a>
        

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

        示例:

        用于创建:

        http://localhost/feed

        编辑:

        http://localhost/feed/1

        【讨论】:

          猜你喜欢
          • 2016-03-23
          • 2016-12-13
          • 1970-01-01
          • 1970-01-01
          • 2015-06-16
          • 1970-01-01
          • 1970-01-01
          • 2013-08-01
          • 2020-06-15
          相关资源
          最近更新 更多