Open In App

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

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

Approach:



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:




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
   
import { AppComponent } from './app.component';
   
const routes: Routes = [
  { path: '', component: AppComponent },
];
   
@NgModule({
  imports:      [ BrowserModule, 
        RouterModule.forRoot(routes) ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts:




import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
    constructor(private router: Router) { }
      
    ngOnInit() {
        this.router.events.subscribe((event) => {
            if (!(event instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}

app.component.html:




<link href=
    rel="stylesheet">
<div class="jumbotron">
    <h1 class="display-4">Hello,Geek!</h1>
    <p class="lead">
        GeeksForGeeks is a website which 
        is a one stop destination for all 
        the computer science related
        doubts.
    </p>
  
    <hr class="my-4">
  
    <p>
        Click on the below button 
        to starting learning.
    </p>
  
    <p class="lead">
        <a class="btn btn-primary btn-lg" 
            href="#" role="button">
            Explore
        </a>
    </p>
</div>
  
<div class="card">
    <div class="card-header">
        Featured
    </div>
    <div class="card-body">
        <h5 class="card-title">
            Front End Technologies
        </h5>
        <p class="card-text">
            HTML, CSS, Javascript, 
            Angular, React.js
        </p>
  
        <a href="#" class="btn btn-primary">
            Start Learning
        </a>
    </div>
</div>
<br>
  
<div class="card">
    <div class="card-header">
        Featured
    </div>
    <div class="card-body">
        <h5 class="card-title">
            Backend Technologies
        </h5>
        <p class="card-text">
            Node.js, Django,Express
        </p>
  
        <a href="#" class="btn btn-primary">
            Start Learning
        </a>
    </div>
</div>

Output:


Article Tags :