I have a directive that prevents scrolling of the parent container, but I got stuck on testing it. How to test this mouse events and the entire directive? Can anyone help me please?
import { Directive, ElementRef, OnInit, OnDestroy, Input, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@Directive({
selector: '[preventParentScroll]'
})
export class PreventScrollDirective implements OnInit, OnDestroy {
private mouseWheelEventHandler = (event: any) => this.onMouseWheel(event);
constructor(private element: ElementRef) {
}
ngOnInit() {
const element: Element = this.element.nativeElement;
element.addEventListener('mousewheel', this.mouseWheelEventHandler);
element.addEventListener('DOMMouseScroll', this.mouseWheelEventHandler);
}
ngOnDestroy() {
const element: Element = this.element.nativeElement;
element.removeEventListener('mousewheel', this.mouseWheelEventHandler);
element.removeEventListener('DOMMouseScroll', this.mouseWheelEventHandler);
}
onMouseWheel(event: any) {
const element: any = this.element.nativeElement;
const { scrollTop, scrollHeight, clientHeight } = element;
const delta = (event.type === 'DOMMouseScroll' ? event.detail * -40 : event.wheelDelta);
const up = delta > 0;
const prevent = () => {
event.stopPropagation();
event.preventDefault();
event.returnValue = false;
return false;
};
if (!up && -delta > scrollHeight - clientHeight - scrollTop) {
element.scrollTop = scrollHeight;
return prevent();
} else if (up && delta > scrollTop) {
element.scrollTop = 0;
return prevent();
}
}
}
Aucun commentaire:
Enregistrer un commentaire