最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 6, scroll to top - Stack Overflow

programmeradmin4浏览0评论

I have e across an issue in my angular 6 application. When the route is appended, the scroll doesn't change its position. I want it to scroll to the top of the page when the route gets appended. http://localhost:4200/#/pending-transfer is the initial route. After the user clicks on a button in the page, the route gets appended to http://localhost:4200/#/pending-transfer/2595/62. I have tried using window.scrollTo(0,0) in ngOnInit(), but that didn't work.

I have e across an issue in my angular 6 application. When the route is appended, the scroll doesn't change its position. I want it to scroll to the top of the page when the route gets appended. http://localhost:4200/#/pending-transfer is the initial route. After the user clicks on a button in the page, the route gets appended to http://localhost:4200/#/pending-transfer/2595/62. I have tried using window.scrollTo(0,0) in ngOnInit(), but that didn't work.

Share Improve this question edited Dec 14, 2018 at 16:47 veben 22.3k15 gold badges69 silver badges83 bronze badges asked Dec 14, 2018 at 12:28 RamyaRamya 2512 gold badges6 silver badges15 bronze badges 2
  • Try it in ngAfterViewInit() – Sonu Kapoor Commented Dec 14, 2018 at 15:34
  • Hey @Ramya, the links you used in your question only point to your local machine. To help us answer your question, can you post some of your code for us to look at to get a better idea of what's going on? Thanks! – Josiah Nunemaker Commented Dec 14, 2018 at 15:41
Add a ment  | 

4 Answers 4

Reset to default 7

If you are using Angular v6 or more, You can simply set this option in extra options of routing configuration like below -

@NgModule({
  imports: [
      RouterModule.forRoot(routes, {
         scrollPositionRestoration: 'top'
      })
  ]
})
export class AppRoutingModule {}

This will always set your scroll position to top while navigation.

For more in details see here -

  • Deep dive into Angular Routing — Scrolling to top, Debugging and lot more

if you are using angular material side nav ponent then use below code:

const element = document.querySelector('mat-sidenav-content') || window;
element.scrollTo(0, 0);

I ran into a similar issue a while back, and this worked for Angular 4. Hopefully, you can use it too. This is in app.ponent.ts:

export class AppComponent {
  constructor(private router: Router, private route: ActivatedRoute, private location: Location) { }

  private lastPoppedUrl: string;
  private yScrollStack: number[] = [];

  ngOnInit() {
    const path = this.route.snapshot.queryParams['path'];
    const navigateTo = '/' + path;

    if (path) {
      this.router.navigate([navigateTo]);
    }

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

  }
}

app.ponent.ts insert this code

    export class AppComponent {
  
  isShow: boolean;
  topPosToStartShowing = 100;

  @HostListener('window:scroll')
  checkScroll() {
      
    const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

    console.log('[scroll]', scrollPosition);
    
    if (scrollPosition >= this.topPosToStartShowing) {
      this.isShow = true;
    } else {
      this.isShow = false;
    }
  }

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

Then open on app.ponent.html create button to top example code :

    <button class="button" *ngIf="isShow" (click)="gotoTop()">
Top ↑ </button>
发布评论

评论列表(0)

  1. 暂无评论