Lets Have a fun with Technology.

BTemplates.com

Follow by Email

Monday, July 3, 2017

Scroll to top of page in Angular 2 (Using routing)


Hello,

Sometime we need to move on next page using clicking on page bottom link.


In Angular 2 there is a problem. Next page will not move directly to the top of the page.


This may give bad impression to end user.


Below is one way to move focus on top of the page.


register a listener of route change on main component and scroll to 

top on route changes.

Shown in below example.



 


import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'main-app',
    template: '',
})

export class MainComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}




You can also used document.body.scrollTop = 0. 

 Hope this will helpful.

0 comments:

Post a Comment