關於angular跳轉路由以後不能自動回到頂部的解決方法

Question: angular2 scroll top on router change

當咱們在第一個路由滑動到底部當咱們點擊導航跳轉到另外一個路由時頁面沒有回到頂部而是保持上一個路由的滾動位置,基本的解決辦法有兩種。angular2

第一種解決方法是在組建的ngOnIinit()中進行調換路由後的重置

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

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

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

第二種解決方法是在import中對路由進行注入的時候設置scrollPositionRestoration參數(angular6以後)。

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})
相關文章
相關標籤/搜索