RED-3800: Redo HasScrollbar directive

This commit is contained in:
Adina Țeudan 2023-09-24 12:19:55 +03:00
parent 890cf417a1
commit 1b76808917

View File

@ -1,27 +1,33 @@
import { ChangeDetectorRef, Directive, ElementRef, HostBinding, HostListener, OnChanges, OnInit } from '@angular/core';
import { ChangeDetectorRef, Directive, ElementRef, HostBinding, OnDestroy, OnInit } from '@angular/core';
@Directive({
selector: '[iqserHasScrollbar]',
standalone: true,
})
export class HasScrollbarDirective implements OnInit, OnChanges {
export class HasScrollbarDirective implements OnInit, OnDestroy {
@HostBinding('class') class = '';
constructor(
protected readonly _elementRef: ElementRef,
protected readonly _changeDetector: ChangeDetectorRef,
) {}
private readonly _resizeObserver: ResizeObserver;
get hasScrollbar() {
const element = this._elementRef?.nativeElement as HTMLElement;
return element.clientHeight < element.scrollHeight;
}
constructor(
protected readonly _elementRef: ElementRef,
protected readonly _changeDetector: ChangeDetectorRef,
) {
this._resizeObserver = new ResizeObserver(entry => {
this.process();
});
this._resizeObserver.observe(this._elementRef.nativeElement);
}
ngOnInit() {
setTimeout(() => this.process(), 0);
}
@HostListener('window:resize')
process() {
const newClass = this.hasScrollbar ? 'has-scrollbar' : '';
if (this.class !== newClass) {
@ -30,7 +36,7 @@ export class HasScrollbarDirective implements OnInit, OnChanges {
}
}
ngOnChanges() {
this.process();
ngOnDestroy() {
this._resizeObserver.unobserve(this._elementRef.nativeElement);
}
}