From 1b76808917fcb3ff2ab6fe377599bb1583515499 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adina=20=C8=9Aeudan?= Date: Sun, 24 Sep 2023 12:19:55 +0300 Subject: [PATCH] RED-3800: Redo HasScrollbar directive --- src/lib/directives/has-scrollbar.directive.ts | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) 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); } }