Filip Witkowski
Filip Witkowski

Reputation: 955

Angular: detect click on current page link

Is there any way to use Angular build in router properties, such as RouterLinkActive to detect click on the link to current page? In the footer I want to add function to scroll to top if clicked on the current page link.

I have this:

<a *ngIf="!sublinkItem.outerLink" [title]="sublinkItem.altText"
  [routerLink]="[sublinkItem.link]" routerLinkActive="active" 
  [routerLinkActiveOptions]="{exact: true}"                                     
  class="dropdown-item outer-link" 
  [innerHTML]="sublinkItem.text">
</a>

And I have function in the component:

scrollToTop(): void {...}

I want to fire this function only, if routerLinkActive is true.

Upvotes: 1

Views: 149

Answers (1)

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8826

You can use the instance reference of the RouterLinkActive directive in your HTML template. Note - I removed some attributes for brevity:

<a 
  [routerLink]="[sublinkItem.link]" 
  routerLinkActive="active"
  #routerLinkActiveRef="routerLinkActive"
  [routerLinkActiveOptions]="{exact: true}"                                     
  (click)="scrollToTop(routerLinkActiveRef.isActive)"
>
 {{ sublinkItem.text }}
</a>

And in your component code:

scrollToTop(shouldScroll: boolean): void {
  if (!shouldScroll) {
    return;
  }

  // scroll!
}

Upvotes: 1

Related Questions