Angular 5 Scroll to top on every Route click

后端 未结 18 1850
遇见更好的自我
遇见更好的自我 2020-11-29 17:49

I am using angular 5. I have a dashboard where I have few sections with small content and few sections with so large content that I am facing a problem when changing router

18条回答
  •  攒了一身酷
    2020-11-29 18:12

    Although @Vega provides the direct answer to your question, there are issues. It breaks the browser's back/forward button. If you're user clicks the browser back or forward button, they lose their place and gets scrolled way at the top. This can be a bit of a pain for your users if they had to scroll way down to get to a link and decided to click back only to find the scrollbar had been reset to the top.

    Here's my solution to the problem.

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

提交回复
热议问题