Whenever the this
keywords are used inside the onScroll
function, they seem to represent the wrong context. Inside the function, it refers to the window
, which is understandable. I was attempting to use the =>
arrow notation to maintain the correct reference to this
, but I couldn't find the right syntax or placement for it in this situation.
Even storing this
in a public self = this
variable didn't work for some reason. However, I would prefer a solution that utilizes the =>
notation.
Below is the structure of the class:
export class ScrollXDirective implements AfterContentInit {
@ContentChild(FormDatepickerPresetsComponent) presets: FormDatepickerPresetsComponent;
public posX: number = 0;
public offset: number = 35;
constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}
ngAfterContentInit() {
let wrapper: HTMLElement = this.presets.presetsWrapperElement.nativeElement;
let scrollHandler: string = 'DOMMouseScroll' in window ? 'DOMMouseScroll' : 'mousewheel';
this._renderer.listen(wrapper, scrollHandler, _.debounce(this.onScroll, 200));
}
onScroll(e: any) {
e.preventDefault();
let delta = (e.type === 'DOMMouseScroll' ? e.detail * -40 : e.wheelDelta);
let list: HTMLElement = this.presets.presetsListElement.nativeElement;
let totalWidth = list.offsetWidth;
if (delta > 0) {
if (this.posX >= 0) {
return false;
}
this.posX = this.posX + this.offset;
this._renderer.setElementStyle(list, 'margin-left', this.posX + 'px');
}
else {
let listX = list.getBoundingClientRect().right;
let hostX = this._elementRef.nativeElement.getBoundingClientRect().right;
if (listX <= hostX) {
return false;
}
this.posX = this.posX - this.offset;
this._renderer.setElementStyle(list, 'margin-left', this.posX + 'px');
}
}
}