Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

angular2 template - Angular: How to determine active route with parameters?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...