[英]Angular 5 Scroll to top on every Route click
我正在使用 Angular 5。我有一个仪表板,其中有几个部分内容很小,而很少有部分内容如此之大,以至于在转到顶部时更换路由器时遇到问题。 每次我需要滚动到 go 到顶部。
如何解决此问题,以便在更改路由器时,我的视图始终保持在顶部?
有一些解决方案,请确保全部检查:)
路由器插座将在实例化新组件时发出activate
事件,因此我们可以使用(activate)
滚动(例如)到顶部:
应用程序组件.html
<router-outlet (activate)="onActivate($event)" ></router-outlet>
app.component.ts
onActivate(event) {
window.scroll(0,0);
//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
...
}
例如,使用此解决方案进行平滑滚动:
onActivate(event) {
let scrollToTop = window.setInterval(() => {
let pos = window.pageYOffset;
if (pos > 0) {
window.scrollTo(0, pos - 20); // how far to scroll on each step
} else {
window.clearInterval(scrollToTop);
}
}, 16);
}
如果你希望有选择性,说不是每个组件都应该触发滚动,你可以在这样的if
语句中检查它:
onActivate(e) {
if (e.constructor.name)==="login"{ // for example
window.scroll(0,0);
}
}
从 Angular6.1 开始,我们还可以在急切加载的模块上使用{ scrollPositionRestoration: 'enabled' }
,它将应用于所有路由:
RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })
它也将进行平滑滚动,已经。 然而,这对于在每条路由上都这样做很不方便。
另一种解决方案是在路由器动画上进行顶部滚动。 在要滚动到顶部的每个过渡中添加以下内容:
query(':enter, :leave', style({ position: 'fixed' }), { optional: true })
如果您在 Angular 6 中遇到这个问题,您可以通过将参数scrollPositionRestoration: 'enabled'
到 app-routing.module.ts 的 RouterModule 来解决它:
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'enabled'
})],
exports: [RouterModule]
})
编辑:对于 Angular 6+,请使用 Nimesh Nishara Indimagedara 的回答提到:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled'
});
原答案:
如果一切都失败了,那么在模板(或父模板)上使用 id="top" 在顶部(或所需的滚动到位置)创建一些空的 HTML 元素(例如:div):
<div id="top"></div>
在组件中:
ngAfterViewInit() {
// Hack: Scrolls to top of Page after page view initialized
let top = document.getElementById('top');
if (top !== null) {
top.scrollIntoView();
top = null;
}
}
现在,Angular 6.1 中有一个内置解决方案,带有scrollPositionRestoration
选项。
尽管@Vega 为您的问题提供了直接答案,但还是存在问题。 它打破了浏览器的后退/前进按钮。 如果您是用户单击浏览器的后退或前进按钮,他们会失去位置并在顶部滚动。 如果您的用户不得不向下滚动才能找到链接,并决定单击返回后才发现滚动条已重置到顶部,那么这对您的用户来说可能会有点痛苦。
这是我对问题的解决方案。
export class AppComponent implements OnInit {
isPopState = false;
constructor(private router: Router, private locStrat: LocationStrategy) { }
ngOnInit(): void {
this.locStrat.onPopState(() => {
this.isPopState = true;
});
this.router.events.subscribe(event => {
// Scroll to top if accessing a page, not via browser history stack
if (event instanceof NavigationEnd && !this.isPopState) {
window.scrollTo(0, 0);
this.isPopState = false;
}
// Ensures that isPopState is reset
if (event instanceof NavigationEnd) {
this.isPopState = false;
}
});
}
}
对于来自@ docs
Angular 版本6+
表示配置路由器的选项。
interface ExtraOptions {
enableTracing?: boolean
useHash?: boolean
initialNavigation?: InitialNavigation
errorHandler?: ErrorHandler
preloadingStrategy?: any
onSameUrlNavigation?: 'reload' | 'ignore'
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
anchorScrolling?: 'disabled' | 'enabled'
scrollOffset?: [number, number] | (() => [number, number])
paramsInheritanceStrategy?: 'emptyOnly' | 'always'
malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
urlUpdateStrategy?: 'deferred' | 'eager'
relativeLinkResolution?: 'legacy' | 'corrected'
}
可以使用scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
示例:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled'|'top'
});
如果需要手动控制滚动,无需使用window.scroll(0,0)
而是从 Angular V6 通用包引入了ViewPortScoller
。
abstract class ViewportScroller {
static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
abstract setOffset(offset: [number, number] | (() => [number, number])): void
abstract getScrollPosition(): [number, number]
abstract scrollToPosition(position: [number, number]): void
abstract scrollToAnchor(anchor: string): void
abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}
用法非常简单示例:
import { Router } from '@angular/router';
import { ViewportScroller } from '@angular/common'; //import
export class RouteService {
private applicationInitialRoutes: Routes;
constructor(
private router: Router;
private viewPortScroller: ViewportScroller//inject
)
{
this.router.events.pipe(
filter(event => event instanceof NavigationEnd))
.subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}
就我而言,我刚刚添加了
window.scroll(0,0);
在ngOnInit()
和它的工作正常。
如果您使用 mat-sidenav 为路由器插座提供一个 ID(如果您有父路由器插座和子路由器插座)并在其中使用激活功能<router-outlet id="main-content" (activate)="onActivate($event)">
并使用这个 'mat-sidenav-content' 查询选择器滚动顶部onActivate(event) { document.querySelector("mat-sidenav-content").scrollTo(0, 0); }
onActivate(event) { document.querySelector("mat-sidenav-content").scrollTo(0, 0); }
Angular 6.1 及更高版本:
您可以使用Angular 6.1+ 中提供的内置解决方案和选项scrollPositionRestoration: 'enabled'
来实现相同的效果。
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'enabled'
})],
exports: [RouterModule]
})
Angular 6.0 及更早版本:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
private lastPoppedUrl: string;
private yScrollStack: number[] = [];
constructor(private router: Router, private location: Location) { }
ngOnInit() {
this.location.subscribe((ev:PopStateEvent) => {
this.lastPoppedUrl = ev.url;
});
this.router.events.subscribe((ev:any) => {
if (ev instanceof NavigationStart) {
if (ev.url != this.lastPoppedUrl)
this.yScrollStack.push(window.scrollY);
} else if (ev instanceof NavigationEnd) {
if (ev.url == this.lastPoppedUrl) {
this.lastPoppedUrl = undefined;
window.scrollTo(0, this.yScrollStack.pop());
} else
window.scrollTo(0, 0);
}
});
}
}
注意:预期的行为是,当您导航回页面时,它应该保持向下滚动到与单击链接时相同的位置,但在到达每个页面时滚动到顶部。
我一直在寻找解决这个问题的内置解决方案,就像在 AngularJS 中一样。 但在那之前,这个解决方案对我有用,它很简单,并且保留了后退按钮的功能。
应用程序组件.html
<router-outlet (deactivate)="onDeactivate()"></router-outlet>
app.component.ts
onDeactivate() {
document.body.scrollTop = 0;
// Alternatively, you can scroll to top by using this other call:
// window.scrollTo(0, 0)
}
您只需要创建一个包含调整屏幕滚动的功能
例如
window.scroll(0,0) OR window.scrollTo() by passing appropriate parameter.
window.scrollTo(xpos, ypos) --> 预期参数。
只需添加
window.scrollTo({ top: 0);
到 ngOnInit()
对于正在寻找滚动功能的人,只需添加该功能并在需要时调用
scrollbarTop(){
window.scroll(0,0);
}
由于某种原因,以上都不适合我:/,所以我在app.component.html
的顶部元素中添加了一个元素引用,并将(activate)=onNavigate($event)
到router-outlet
。
<!--app.component.html-->
<div #topScrollAnchor></div>
<app-navbar></app-navbar>
<router-outlet (activate)="onNavigate($event)"></router-outlet>
然后我说孩子的app.component.ts文件类型ElementRef
,并且有它滚动到它的路由器出口的激活。
export class AppComponent {
@ViewChild('topScrollAnchor') topScroll: ElementRef;
onNavigate(event): any {
this.topScroll.nativeElement.scrollIntoView({ behavior: 'smooth' });
}
}
这是stackblitz中的代码
这是一个仅在第一次访问每个组件时滚动到组件顶部的解决方案(以防您需要为每个组件做一些不同的事情):
在每个组件中:
export class MyComponent implements OnInit {
firstLoad: boolean = true;
...
ngOnInit() {
if(this.firstLoad) {
window.scroll(0,0);
this.firstLoad = false;
}
...
}
试试这个:
app.component.ts
import {Component, OnInit, OnDestroy} from '@angular/core';
import {Router, NavigationEnd} from '@angular/router';
import {filter} from 'rxjs/operators';
import {Subscription} from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit, OnDestroy {
subscription: Subscription;
constructor(private router: Router) {
}
ngOnInit() {
this.subscription = this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(() => window.scrollTo(0, 0));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
export class AppComponent { constructor(private router: Router) { router.events.subscribe((val) => { if (val instanceof NavigationEnd) { window.scrollTo(0, 0); } }); } }
组件:订阅所有路由事件而不是在模板中创建一个动作并在 NavigationEnd b/c 上滚动,否则你会在错误的导航或阻塞的路由等上触发它......这是一个确定的方法来知道如果成功导航到一条路线,然后平滑滚动。 否则,什么都不做。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
router$: Subscription;
constructor(private router: Router) {}
ngOnInit() {
this.router$ = this.router.events.subscribe(next => this.onRouteUpdated(next));
}
ngOnDestroy() {
if (this.router$ != null) {
this.router$.unsubscribe();
}
}
private onRouteUpdated(event: any): void {
if (event instanceof NavigationEnd) {
this.smoothScrollTop();
}
}
private smoothScrollTop(): void {
const scrollToTop = window.setInterval(() => {
const pos: number = window.pageYOffset;
if (pos > 0) {
window.scrollTo(0, pos - 20); // how far to scroll on each step
} else {
window.clearInterval(scrollToTop);
}
}, 16);
}
}
HTML
<router-outlet></router-outlet>
试试这个
@NgModule({
imports: [RouterModule.forRoot(routes,{
scrollPositionRestoration: 'top'
})],
exports: [RouterModule]
})
此代码支持角度 6<=
对我有用的解决方案:
document.getElementsByClassName('layout-content')[0].scrollTo(0, 0);
它适用于角度 8、9 和 10。
只需在app.module.ts
文件中添加这一行:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled' //scroll to the top
})
我正在使用 Angular 11.1.4,它对我有用
只需添加
ngAfterViewInit() {
window.scroll(0,0)
}
刚刚想通了。
路由驱动到的组件:
ngAfterViewInit(): void {
this.commonService.scrollTo('header', BEHAVIOR.auto)
}
服务:
scrollTo(element: string, behavior: BEHAVIOR): void {
(document.getElementById(element) as HTMLElement).scrollIntoView({behavior: behavior, block: "start", inline: "nearest"});
}
枚举:
export enum BEHAVIOR {
smooth = 'smooth',
auto = 'auto'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.