Angular 2 中的浏览器样式滚动行为
Browser style scroll behaviors in Angular 2
在 React 中有一个叫做 react-router-scroll 的东西:https://www.npmjs.com/package/react-router-scroll。它使 React 应用程序页面像普通站点一样滚动。所以它滚动到每个新页面(路由)的顶部,并保留过去页面的滚动位置;当您单击后退按钮时,它会记住您在该页面上滚动到的位置。
我正在 Angular2 中寻找类似的东西。我搜索并没有找到类似的东西。应该在外面的某个地方。
订阅路线变更
您可以订阅路线事件,当用户导航到新路线时,您可以将 document.body.scrollTop
设置为 0。确保将其包含在将为任何请求的路线加载的根级组件中.
组件
import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
document.body.scrollTop = 0;
}
});
}
}
我创建了一个模块,您可以像这样使用它:
1-
npm install scrollstore
2- 转到您的 app.module(导入所有根模块的位置)。
import { ScrollStoreModule } from 'scrollStore';
3- 将 ScrollStoreModule 添加到您的应用模块
@NgModule({
bootstrap: [ AppComponent ],
imports: [
ScrollStoreModule, // put it here
BrowserModule,
FormsModule,
HttpModule
.. rest of your modules ....
]
})
export class AppModule {
...
就是这样。
id 的作用:
在更改路线之前保存路线名称,当您返回时如果保存的路线存在于 sessionStorage 中,它将滚动到该位置,否则它将滚动到页面顶部。
随时contribute。
在 React 中有一个叫做 react-router-scroll 的东西:https://www.npmjs.com/package/react-router-scroll。它使 React 应用程序页面像普通站点一样滚动。所以它滚动到每个新页面(路由)的顶部,并保留过去页面的滚动位置;当您单击后退按钮时,它会记住您在该页面上滚动到的位置。
我正在 Angular2 中寻找类似的东西。我搜索并没有找到类似的东西。应该在外面的某个地方。
订阅路线变更
您可以订阅路线事件,当用户导航到新路线时,您可以将 document.body.scrollTop
设置为 0。确保将其包含在将为任何请求的路线加载的根级组件中.
组件
import { Component, OnInit } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
document.body.scrollTop = 0;
}
});
}
}
我创建了一个模块,您可以像这样使用它:
1-
npm install scrollstore
2- 转到您的 app.module(导入所有根模块的位置)。
import { ScrollStoreModule } from 'scrollStore';
3- 将 ScrollStoreModule 添加到您的应用模块
@NgModule({
bootstrap: [ AppComponent ],
imports: [
ScrollStoreModule, // put it here
BrowserModule,
FormsModule,
HttpModule
.. rest of your modules ....
]
})
export class AppModule {
...
就是这样。
id 的作用:
在更改路线之前保存路线名称,当您返回时如果保存的路线存在于 sessionStorage 中,它将滚动到该位置,否则它将滚动到页面顶部。
随时contribute。