Autoscroll in Angular 2

后端 未结 10 1176
清歌不尽
清歌不尽 2020-12-01 12:21

I\'m experiencing an issue with Angular 2 where changing from one route to another does not automatically scroll to the top of the new view. I realize that Angular 1 allowed

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 13:09

    Has you can see here: https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#events-anchor, you have to use "router.events.subscribe" since Angular 2.0.0

    So a good solution to automaticly scrool to the top of all page is to have a AppComponent like this:

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

提交回复
热议问题