Autoscroll in Angular 2

后端 未结 10 1143
清歌不尽
清歌不尽 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:06

    I had the same issue. Based on Gunter's answer I found that Angular's 2 RC.1 new router doesn't expose an Observable directly. Instead it has a changes property for that purpose. The workaround for RC.1 is:

    this._router.changes.subscribe(() => {
        window.scrollTo(0, 0);
    }); 
    
    0 讨论(0)
  • 2020-12-01 13:08

    I'm using material sidenav and I couldn't get any of the suggested answers to work for me. Here's my working solution:

    import { Router, NavigationEnd } from '@angular/router';
    
    ...
    
    constructor(
      private router: Router,
    ) {
      router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
          document.querySelector('.mat-sidenav-content').scrollTop = 0;
        }
      }
    }
    
    0 讨论(0)
  • 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);
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-01 13:09

    I have used if(this.router.navigated) in the ngOnInit of each page to determine whether or not to use window.scrollTo(0, 0). This will cover most cases of routing to the page, while leaving the scroll position where it should be if you click the browser Back button.

    if(this.router.navigated) {
      window.scrollTo(0, 0);
    }
    
    0 讨论(0)
提交回复
热议问题