Can't Figure Out Why Page Loads at Bottom? Angular Ui-Router Autoscroll Issue

Can't figure out why page loads at bottom? Angular UI-Router autoscroll Issue

Angular UI-Router recently updated it's app so that it automatically scrolls down to new views loaded by default. This was causing my app's pages to load scrolled down. To turn this off simply add the following attribute to your ui-view:

<div ui-view="header" autoscroll="true"></div>

Angular 5 Scroll to top on every Route click

There are some solutions, make sure to check them all :)


Option1:

The router outlet will emit the activate event any time a new component is being instantiated, so we could use (activate) to scroll (for example) to the top:

app.component.html

<router-outlet (activate)="onActivate($event)"></router-outlet>

app.component.ts

onActivate(event) {
// window.scroll(0,0);

window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});

//or document.body.scrollTop = 0;
//or document.querySelector('body').scrollTo(0,0)
...
}

As the smooth scroll is not implemented well in Safari, use, for exemple, this solution for a smooth scroll:

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 you wish to be selective, say not every component should trigger the scrolling, you can check it in an if statement like this:

onActivate(e) {
if (e.constructor.name)==="login"{ // for example
window.scroll(0,0);
}
}

Option2:

Since Angular6.1, we can also use { scrollPositionRestoration: 'enabled' } on eagerly loaded modules and it will be applied to all routes:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })

It will also do the smooth scrolling, already. However this has the inconvenient for doing it on every routing.


Option3:

An other solution is to do the top scrolling on router animation. Add this in every transition where you want to scroll to the top:

query(':enter, :leave', style({ position: 'fixed' }), { optional: true }) 

Angular 2 Scroll to top on Route Change

Angular 6.1 and later:

Angular 6.1 (released on 2018-07-25) added built-in support to handle this issue, through a feature called "Router Scroll Position Restoration". As described in the official Angular blog, you just need to enable this in the router configuration like this:

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

Furthermore, the blog states "It is expected that this will become the default in a future major release". So far this hasn't happened (as of Angular 11.0), but eventually you won't need to do anything at all in your code, and this will just work correctly out of the box.

You can see more details about this feature and how to customize this behavior in the official docs.

Angular 6.0 and earlier:

While @GuilhermeMeireles's excellent answer fixes the original problem, it introduces a new one, by breaking the normal behavior you expect when you navigate back or forward (with browser buttons or via Location in code). The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page obviously breaks this expectation.

The code below expands the logic to detect this kind of navigation by subscribing to Location's PopStateEvent sequence and skipping the scroll-to-top logic if the newly arrived-at page is a result of such an event.

If the page you navigate back from is long enough to cover the whole viewport, the scroll position is restored automatically, but as @JordanNelson correctly pointed out, if the page is shorter you need to keep track of the original y scroll position and restored it explicitly when you go back to the page. The updated version of the code covers this case too, by always explicitly restoring the scroll position.

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);
}
});
}
}

On route change view doesn't scroll to top in the new page in angular2

found answer here https://stackoverflow.com/a/39601987/5043867

we can subscribe to the route change event and scroll to the top with something in the lines of

ngOnInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
document.body.scrollTop = 0;
});
}

Update -

In Angular v6+ there is a new method scrollPositionRestoration introduced. for more info read out here

  • https://medium.com/@PardeepJain/deep-dive-into-angular-routing-scrolling-to-top-debugging-and-lot-more-a995c08498d3

Can't figure out why my angular view is blank

Two things that I see would break your angular bootstrap process:

First, include your app.js last:

<script src="scripts/controllers/main.js"></script>
<script src="scripts/app.js"></script>

Then, .config should come before .run:

'use strict';

angular.module('angularApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ui.router'
])

.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {}
])

.run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {}
]);


Related Topics



Leave a reply



Submit