VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/how-to-scroll-to-top-on-every-route-click-in-angular5/

⇱ How to scroll to top on every Route click in Angular5 ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to scroll to top on every Route click in Angular5 ?

Last Updated : 6 Aug, 2024

We can use Router and NavigationEnd from '@angular/router' and hence we can scroll to the top of the webpage for every route.

Approach:

  • First, we need to import the Router and NavigationEnd from '@angular/router' in both app.module.ts file and app.component.ts.
  • Then we need to create an instance of those in the constructor function.
  • After creating the instance we need to use them in the ngOninit() life cycle hook.
  • In the ngOninit() hook, we need to subscribe to the events of the router and check whether it is an instance of NavigationEnd or not.
  • Then after checking we can use the window.scrollTo() function with (0,0) coordinates to navigate to the top.

After following the above steps start your project using the below command.

ng serve --open

Below is the implementation of the above steps:

app.module.ts:


app.component.ts:


app.component.html:

Output:

Comment
Article Tags:

Explore