creativetimofficial / ct-light-bootstrap-dashboard-pro-angular

7 stars 2 forks source link

Scroll to top on route change #27

Closed puddings closed 5 years ago

puddings commented 5 years ago

I'm having this issue where the main-panel will not scroll to top on route change (selecting a different page from the sidebar).

I realized this issue is happening on the Live Demo site as well.

I have tried using scrollPositionRestoration: 'enabled' and it did not work. The issue is due to the .main-panel height: 100% and min-height: 100%.

Any help would be greatly appreciated.

Thank you.

chelaruc commented 5 years ago

@puddings add this in admin.layout.ts in the component:

private _router: Subscription;
    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];
    url: string;

and in ngOnInit:

const elemMainPanel = <HTMLElement>document.querySelector('.main-panel');
        const elemSidebar = <HTMLElement>document.querySelector('.sidebar .sidebar-wrapper');
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
         this.router.events.subscribe((event:any) => {
            if (event instanceof NavigationStart) {
               if (event.url != this.lastPoppedUrl)
                   this.yScrollStack.push(window.scrollY);
           } else if (event instanceof NavigationEnd) {
               if (event.url == this.lastPoppedUrl) {
                   this.lastPoppedUrl = undefined;
                   window.scrollTo(0, this.yScrollStack.pop());
               }
               else
                   window.scrollTo(0, 0);
           }
        });
        this._router = this.router.events.filter(event => event instanceof NavigationEnd).subscribe((event: NavigationEnd) => {
             elemMainPanel.scrollTop = 0;
             elemSidebar.scrollTop = 0;
        });

and declare imports:

import { Router, NavigationEnd, NavigationStart } from '@angular/router';
import { NavItem, NavItemType } from '../../md/md.module';
import { Subscription } from 'rxjs/Subscription';
import { Location, LocationStrategy, PathLocationStrategy, PopStateEvent } from '@angular/common';
import 'rxjs/add/operator/filter';

Tell me if it's working.

puddings commented 5 years ago

Thank you for your reply. I have tested your code and it is working as intended.

I did not have this import though:

import { NavItem, NavItemType } from '../../md/md.module';

Thanks again for your help.