COMPONENTE SCROLL TOP BUTTON (ANGULAR)

Code with Edd

CREAR UN COMPONENTE PARA TENER UN SCROLL TOP BUTTON EN LA NAVEGACIÓN DE NUESTRA APLICACIÓN WEB CON ANGULAR.

Creamos nuestro componente con nuestra consola:

ng generate component components/scrolltotop

En nuestro componente del archivo .html agregaremos el siguiente código:

<div class="scroll-to-top" [ngClass]="{'show-scrollTop': windowScrolled}">
    <button type="button" class="btn active" data-toggle="button" aria-pressed="true" (click)="scrollToTop()">
        <i class="pi pi-chevron-up pi-22" ></i>
    </button>
</div>

En nuestro componente del archivo .ts agregaremos el siguiente código:

import { Component, OnInit, Inject, HostListener } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-scrolltotop',
  templateUrl: './scrolltotop.component.html',
  styleUrls: ['./scrolltotop.component.css']
})
export class ScrolltotopComponent implements OnInit {
  windowScrolled: boolean;

  constructor(@Inject(DOCUMENT) private document: Document) {
    this.windowScrolled = false;
  }

  @HostListener('window:scroll', [])

  onWindowScroll(): void {
      if (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop > 100) {
          this.windowScrolled = true;
      }
     else if (this.windowScrolled && window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop < 10) {
          this.windowScrolled = false;
      }
  }
  scrollToTop(): void {
      (function smoothscroll(): void {
          const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
          if (currentScroll > 0) {
              window.requestAnimationFrame(smoothscroll);
              window.scrollTo(0, currentScroll - (currentScroll / 8));
          }
      })();
  }

  ngOnInit(): void {
  }

}

En nuestro archivo CSS ya sea uno global o el archivo .css de nuestro componente, agregaremos el siguiente código:

/* SCROLL TO TOP
----------------------------------------------------*/
.scroll-to-top {
  position: fixed;
  bottom: 15px;
  right: 15px;
  opacity: 0;
  transition: all .2s ease-in-out;
  background-color: #858796;
  border-radius: 0.50rem;
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
  z-index: 1000!important;
}
.show-scrollTop {
  opacity: 1;
  transition: all .1s ease-in-out;
}

Y por ultimo agregaremos nuestro nuevo componente a los archivos .htm de los componentes donde queremos que se muestre.

<app-scrolltotop></app-scrolltotop>

Referencia: https://www.techtrek.io/Adding-a-Scroll-to-Top-button-in-Angular/

COMPONENTE SCROLL TOP BUTTON (ANGULAR)
Web | + posts

Full Stack Web Developer && SDK SAPB1 Developer.

Melómano, Gamer (Xbox), Comprador compulsivo de Amazon y Posiblemente con TDAH.

Scroll hacia arriba