2

I am using angular 5 and cli version is 1.5.2 and i am facing issues with routing.

When navigating from one route to another then scrolling down a bit and navigate back to the previous route, the page remains at the same scroll position. Currently navigate from one view to another then scroll down a bit and navigate back to the previous view. the page remains at the same scroll position.

But i need page to be scrolled to the top when navigating from one route to another.

Also i need to know whether this is the default routing behaviour in angular?

JpG
  • 774
  • 8
  • 22
  • People have been providing their answers to this question for quite some time now. This is the latest that I’ve seen https://stackoverflow.com/questions/48048299/angular-5-scroll-to-top-on-every-route-click I’ve provided my own version of an answer. I feel the accepted answer only introduces more problems as it breaks the original functionality of the browser back and forward buttons. My answer solves the problem and keeps the browser back and forward functionalities intact. – Molasses Mar 13 '18 at 03:54

3 Answers3

1

Angular team has resolved this issue in Angular 6.1 with scrollPositionRestoration option.

See my ans: https://stackoverflow.com/a/51915623/4899523

Abdul Rafay
  • 3,241
  • 4
  • 25
  • 50
0

You can register a route change listener

constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0) // for example
        });
    }
santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • 1
    I have added these code snippet in my app-component.ts file, but the problem here is if i do navigate back to previous component it will take me top of the page of previous component, which is not correct. That means that code will always scroll to top on all routing. It breaks the default "back" button behaviour. Going back should remember the previous scroll position. – JpG Jan 03 '18 at 10:30
-1

If you want to only want to scroll to the top when navigating from the home component to another, be sure to unsubscribe afterward. By unsubscribing, you can make sure to not break the default "back" button behavior.

subs: Subscription;  
constructor(private router: Router) { }

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