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