简体   繁体   中英

Angular2 Selects 2 routes with routerLinkActive

I have 2 routes

{ path: '', component: DefaultComponent },
{ path: 'second', component: SecondComponent }

And in html

<a [routerLink]="['/']" [routerLinkActive]="['active']">default</a>
<a [routerLink]="['/second']" [routerLinkActive]="['active']">second</a>

When I navigate to the second one both of them have active class. Is this a bug or a wanted

Using:

    "@angular/router": "~3.3.0",

You can achieve what you expect when you add pathMatch: 'full' to your route config:

{ path: '', component: DefaultComponent, pathMatch: 'full' },
{ path: 'second', component: SecondComponent }

Then the first route will just activate if the complete path is matching, not only if a part of the path is matching.

See: Routing & Navigation

You have to set the [routerLinkActiveOptions]="{exact: true}" attribute, to match the exact path as mentioned in the docs for RouterLinkActive .

If you're setting {exact: true} the router is checking for path equality ( equalSegmentGroups() ), otherwise it's just checking for partial segments ( containsSegmentGroup() ).

See: @angular/router/src/url_tree.ts#L17

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM