Skip to content

Instantly share code, notes, and snippets.

@gmorel
Created September 22, 2017 12:29
Show Gist options
  • Save gmorel/c3d1edd7cf91dfbe379ed09ae81c7cbe to your computer and use it in GitHub Desktop.
Save gmorel/c3d1edd7cf91dfbe379ed09ae81c7cbe to your computer and use it in GitHub Desktop.
Allow to scroll horizontally
import {ElementRef, Injectable} from "@angular/core";
@Injectable()
export class DataTableHorizontalScroller {
private static readonly DATATABLE_BODY_CSS_SELECTOR = '.datatable-body';
private static readonly SCROLL_DISTANCE_IN_PX = 100;
private lastScrollLeft: number;
public constructor(
private elementRef: ElementRef,
) {}
/**
* @returns {boolean} False if no more horizontal scroll possible
*/
public scrollLeft(): boolean {
let dataTableBodyDom = this.elementRef.nativeElement.querySelector(DataTableHorizontalScroller.DATATABLE_BODY_CSS_SELECTOR);
if (this.isMaxScrollLeftReached()) {
return false;
}
let previous: number = DataTableHorizontalScroller.SCROLL_DISTANCE_IN_PX;
this.lastScrollLeft = dataTableBodyDom.scrollLeft;
dataTableBodyDom.scrollLeft -= previous;
return true;
}
/**
* @returns {boolean} False if no more horizontal scroll possible
*/
public scrollRight(): boolean {
let dataTableBodyDom = this.elementRef.nativeElement.querySelector(DataTableHorizontalScroller.DATATABLE_BODY_CSS_SELECTOR);
if (this.isMaxScrollRightReached()) {
return false;
}
let next: number = DataTableHorizontalScroller.SCROLL_DISTANCE_IN_PX;
this.lastScrollLeft = dataTableBodyDom.scrollLeft;
dataTableBodyDom.scrollLeft += next;
return true;
}
private isMaxScrollLeftReached(): boolean {
let next: number = this.createNextScrollDistance();
return next <= DataTableHorizontalScroller.SCROLL_DISTANCE_IN_PX;
}
private isMaxScrollRightReached(): boolean {
let dataTableBodyDom = this.elementRef.nativeElement.querySelector(DataTableHorizontalScroller.DATATABLE_BODY_CSS_SELECTOR);
let maxScroll: number = dataTableBodyDom.scrollWidth - dataTableBodyDom.clientWidth;
let next: number = this.createNextScrollDistance();
return next > maxScroll;
}
private createNextScrollDistance(): number {
let dataTableBodyDom = this.elementRef.nativeElement.querySelector(DataTableHorizontalScroller.DATATABLE_BODY_CSS_SELECTOR);
return dataTableBodyDom.scrollLeft + DataTableHorizontalScroller.SCROLL_DISTANCE_IN_PX;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment