Scroll to the top on Angular route change
Published on January 16, 2018. Edited on June 11, 2019.
By default, Angular doesn't scroll to the top of the page when you're navigating to another page. Here is a quick tip on how to implement scrolling.
Implement a scroll service
At first, create a new service called ScrollTopService
. On a server side (Angular Universal) we don't need this "hack" so it's limited only to a browser.
scrolltop.service.ts
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { isPlatformBrowser } from '@angular/common';
@Injectable()
export class ScrollTopService {
constructor(
@Inject(PLATFORM_ID) private platformId: Object,
private router: Router) {
}
setScrollTop() {
if (isPlatformBrowser(this.platformId)) {
this.router.events.subscribe((event: NavigationEnd) => {
window.scroll(0, 0);
});
}
}
}
Register the service by adding it into app.module.ts
import { ScrollTopService } from 'your/path/scrolltop.service';
@NgModule({
...
providers: [
ScrollTopService,
...
]
})
Inject the service into a component
Inject new service into a component and then call the setScrollTop
method on ngInit
to initialize scrolling.
Example app.component.ts
import {
Component,
OnInit
} from '@angular/core';
import { ScrollTopService } from 'your/path/scrolltop.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private scrollTopService: ScrollTopService
) {}
ngOnInit() {
this.scrollTopService.setScrollTop();
}
}
Edited on 11th of June, 2019
Latest blog posts
October 24, 2019
How to fetch your public photos from Instagram without the API
June 12, 2019
CodePen embeds with Contentful and Angular
March 26, 2019
Global HTTP request and response handling with the Axios interceptor
December 2, 2018
Setting up webpack 4 for a project
November 10, 2018
How to create Material Design like form text fields with floating label and animated underline bar
May 2, 2018
How to build a complete form with Vue.js
April 4, 2018
How to transfer the Angular server-side state to the client-side
March 28, 2018
My web developer career story
Latest CodePens
July 9, 2019
Switch between the dark and light mode via CSS custom properties
June 12, 2019
Javascript URL handling
June 9, 2019
Material Design like form input text fields with CSS only
March 27, 2019
Global HTTP request and response handling with the Axios interceptors
March 23, 2019
Navigation wizard example with equal width steps and flexible width of last step
March 23, 2019
Javascript event delegation example
December 9, 2018
Responsive and animated D3.js bar chart with positive and negative values (TypeScript)
November 11, 2018