Jo Gecale
Jo Gecale

Reputation: 11

Angular 2 scroll to top after loading

I am adding a loading while getting a data. And in my view list there are pagination and page size. So my problem is that whenever I tried to change the page size and move to other pages right after loading it doesn't move scroll to the top. I already added this.document.body.scrollTop = 0; after my loading but it doesn't work.

These are my code in getting a data:

`getProducts() {
    this.productService
       .getProducts(this.args)
       .subscribe(
          data => {
              this.data = data;
              this.loadingService.hide();
              this.document.body.scrollTop = 0;
          },
          (error) =>
                console.log(error);
          }       
      );
    }`

Upvotes: 0

Views: 5686

Answers (3)

Johnyoat
Johnyoat

Reputation: 456

Use window.scrollTo(0,0); in ngOnit. So it should look like this

ngOnInit() { window.scrollTo(0,0); }

Upvotes: 2

cetinDev
cetinDev

Reputation: 319

 import { Component, ViewChild } from '@angular/core';
    import { Content } from 'ionic-angular';

    @Component({...})
    export class MyPage{
      @ViewChild(Content) content: Content;

add to inside subscribe

this.content.scrollToTop();

Referance; http://ionicframework.com/docs/api/components/content/Content/

Upvotes: 0

Chandru
Chandru

Reputation: 11184

Try like this :

component.html

<button class="btn btn-info" (click)="goTop()">goTop</button>

component.ts

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

export class Component {
    constructor(
        @Inject(DOCUMENT) private document: Document
    ) {}
    goTop() {
        this.document.body.scrollTop = 0;
    }
}

Upvotes: 1

Related Questions