Angular: How to determine active route with parameters?

扶醉桌前 提交于 2019-12-17 20:34:25

问题


I've read this question about how to determine the active route, but still it's not clear to me how to determine an active route with paramaters?

Right now I'm doing it like this:

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

And inside my component:

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

And this will work because I'm passing the username as a string. Is there any way to do this with passing the correct parameter??


回答1:


Just check the auto-defined router-link-active class to a element.




回答2:


With the new, up and coming Angular 2 router (at version 3.0-alpha.7 as I write this), it's very simple.

All you need to do is use the [routerLinkActive] directive in your link.

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

This is what you will be using when Angular 2 is released for real, and no longer a release candidate. I'm using the alpha of the router now and not having any issues.

Here's Plunk demonstrating it. You can see that the links go red as you click on them. That's the directive assigning the active class to them. You could use any class name of your choosing, of course.




回答3:


In Angular 2 rc1 router.isRouteActive does not exist anymore. I could not find a working solution anywhere, but I was able to solve it like this (the custom method isActiveRoute does the trick):

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>



回答4:


I've been trying to set the active class without having to know exactly what's the current location (using the route name). This is the best solution I have got to so far.

This is how the RouteConfig looks like (I've tweaked it a bit to look like what you want to do):

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

And the View would 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.




回答5:


You can use new Location service from Angular2 common package: 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.

Please note: Documentation says import from router, but the latest betta version I have has Location services in common.




回答6:


try this :

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



回答7:


For Angular version 4+, determining a active route in the template is fairly easy as there is a build-in directive for this purpose name routerLinkActive which you can use the following way:

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


来源:https://stackoverflow.com/questions/34571517/angular-how-to-determine-active-route-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!