diff --git a/src/lib/directives/has-scrollbar.directive.ts b/src/lib/directives/has-scrollbar.directive.ts index 3b94ed5..eefd625 100644 --- a/src/lib/directives/has-scrollbar.directive.ts +++ b/src/lib/directives/has-scrollbar.directive.ts @@ -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); } }