1

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.

1 Answer 1

1

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!
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.