Router link to scroll on top if its already on that route

448 views Asked by At

Lets say I'm at the bottom of my home page and I click on my logo, Now because the logo routes me to my home page and that I'm already at my home page. It should scroll me to the top of the page. How do I implement this.

Homepage Component HTML

<a routerLink="">
  <img src="../assets/Logo.png" alt="" />
</a>

App Routing Module

  {
    path: '',
    component: HomeComponent,
  },
1

There are 1 answers

0
AudioBubble On

Scrolling to top is, if you have a "normal" page, basically done with:

window.scrollTo(0, 0);

But you have to recognize that a routing event happened either. So put this code into your ngOnInit().

this.router.events.subscribe((event: Event) => {
    if (event instanceof NavigationEnd) {
        window.scrollTo(0, 0);
    }
}