MT.
MT.

Reputation: 25

Add a directive to an UI element when the routerLink is active in angular2

I'm currently working with angular2 and material2. My goal is to change the md-button to md-raised-button when my routerLinkActive is active. For example, if I am on "/todos", I want the "md-button" directive to be replaced by "md-raised-button".

I can't find any solution over the internet, I hope someone can guide me. I would love to avoid using a CSS class.

<a md-button routerLink="/" routerLinkActive="toolbar-active" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>
<a md-button routerLink="/todos" routerLinkActive="toolbar-active" [routerLinkActiveOptions]="{exact: true}">
  Todos
</a>

Thanks for your help!

Mathieu

Upvotes: 1

Views: 435

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

I don't think there is an easier way.

<a md-button #rlActive="routerLinkActive" [hidden]="!rlActive.active" routerLink="/" routerLinkActive="toolbar-active" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>
<a md-button-raised #rlActive="routerLinkActive" [hidden]="rlActive.active" routerLink="/" routerLinkActive="toolbar-active" [routerLinkActiveOptions]="{exact: true}">
  Home
</a>

<a md-button #rlActive="routerLinkActive" [hidden]="!rlActive.active" routerLink="/todos" routerLinkActive="toolbar-active" [routerLinkActiveOptions]="{exact: true}">
  Todos
</a>
<a md-button-raised #rlActive="routerLinkActive" [hidden]="rlActive.active" routerLink="/todos" routerLinkActive="toolbar-active" [routerLinkActiveOptions]="{exact: true}">
  Todos
</a>

If you need this often, I'd wrap the button into a custom component to make it easier to reuse this pattern.

Upvotes: 1

Related Questions