Friday, September 22, 2017

Angular window scroll up using a component

Let us check how we can scroll up the page/window using angular. I will be creating a simple component that can be placed anywhere in the page and user can click on the button to scroll up the page. Same logic I have done in Angular js 1 by using a directive, if you want to check angular js 1 way of implementation for comparing the difference in angular 1 and 2, please click here.

Angular scroll up component


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

@Component({
  selector: 'scroll-up',
  template:'<button *ngIf="showButton" (click)="scrollToTop()">'
            +'Click here to scroll up'
        +'</button>'
})
export class ScrollUpComponent {
  
  showButton : boolean;
  
  constructor(@Inject(DOCUMENT) private document: Document) { 
      this.showButton = false;
  }

  @HostListener("window:scroll", [])
  
  onWindowScroll() {
    
    const scrollTopHeight = document.body.scrollTop || 0;
    
    if(scrollTopHeight > 200)
    {
        this.showButton = true;
    }else
    {
        this.showButton = false;
    }
  }
  scrollToTop()
  {
    this.document.body.scrollTop = 0;
  }
}

We are done. This button will be visible only if our condition is true (here 200). I have used ngIf to show or hide the button. Don’t forget to import the dependencies like Inject, HostListener etc.

In this article we have discussed about creating a simple component which will help users to scroll up the page.

Related Info

1. Share data between components using a service file.

2. Create reusable component and share data between them.

3. Angular client side pagination.

4. Angular show more/less pagination

1 comment :

  1. Thanks for This Component, its will help to simple project, angularsjs one best java scrip framework, developer must join AngularJs Course and become an angularjs Expert

    ReplyDelete