【问题标题】:page not load from top when navigate to new page in angular以角度导航到新页面时页面未从顶部加载
【发布时间】:2018-04-28 10:10:51
【问题描述】:

这是由ng new 命令无库生成的基本 Angular 5 应用程序 添加了我所更改的内容如下所述

角度版本:5.2.0

如果有人想查看完整代码或测试应用,请访问此链接。 github repo

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes} from '@angular/router';

import { AppComponent } from './app.component';
import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';


const RoutesArray: Routes = [
  { path: 'page1' , component: Page1Component },
  { path: 'page2' , component: Page2Component }
];


@NgModule({
 declarations: [
    AppComponent,
    Page1Component,
    Page2Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(RoutesArray)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<nav>
  <a [routerLink]="['/page1']" routerLinkActive="active">Page 1</a>
  <a [routerLink]="['/page2']" routerLinkActive="active">Page 2</a>
</nav>

<div class="pointer">
  <span class="line"></span>
  <span class="arrow"></span>
</div>

<router-outlet></router-outlet>

page1.component.html 和 page2.component.html

<header>
  PAGE 1
  <!-- PAGE 2 -->
</header>

<div class="scale">
  <span>0</span>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>7</span>
  <span>8</span>
  <span>9</span>
  <span>10</span>
  <span>11</span>
  <span>12</span>
</div>

如果我在第 1 页并向下滚动页面然后导航到第 2 页,则第 2 页从我在第 1 页滚动的相同滚动位置加载

我希望第 2 页应该从顶部加载而不是这个,无论我在上一页上滚动了多少。

任何建议如何实现这一点。

【问题讨论】:

    标签: angular


    【解决方案1】:

    将此添加到您的 AppComponent

    第一次导入这个

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

    然后在你的构造函数中

    constructor(private router: Router){
       //subscribes every changes of your route
       this.router.events.subscribe((event) => {
           if (event instanceof NavigationEnd){
              //scroll to top
              window.scrollTo(0,0);
           }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-29
      • 2017-10-22
      • 1970-01-01
      • 2021-11-11
      相关资源
      最近更新 更多