Thorsten Westheider
Thorsten Westheider

Reputation: 10932

Set state based on current route in Angular2 (RC3)

Let's say I have the typical setup, a side menu where I can pick an option and an area to the right where the content for this option is displayed.

I'd like to build the side menu using a series of routerLink directives like so:

@Component({
selector: 'side-menu',
template: `
    <div>
        <ul>
            <li><a [routerLink]="['/option1']">Option 1</a></li>
            <li><a [routerLink]="['/option2']">Option 2</a></li>
            <li><a [routerLink]="['/option3']">Option 3</a></li>
        </ul>
    </div>
`
})

In addition, I'd like the corresponding <li> to be highlighted, using class="active", for example. How do I do that?

Of course, there's always click() plus event handler, but I figure using just routerLink here is much cleaner than handling events.

I'd like to provide a plnkr, but it seems the current Angular2 template is broken once you import from @angular/router, I guess that is because of the router bundle missing from RC3 in the npm.

Upvotes: 0

Views: 734

Answers (1)

Pardeep Jain
Pardeep Jain

Reputation: 86740

I'd like the corresponding <li> to be highlighted, using class="active", for example. How do I do that?

As we know angular2's router chnages continuesly so ASAIK with new router of angular2 this is very easy using routerLinkActive directive in your routerLink . for example

<a [routerLinkActive]="['active']" [routerLink]="['/Demo']">
    Hello Link
</a>

here is working plunker Working Example

also there are many similer question are there

Update

sometimes it throw error

Cannot read property 'pathsWithParams' of undefined so you have to define this as well with routerLinkActive

[routerLinkActiveOptions]="{exact:true}" 

see here

Upvotes: 2

Related Questions