import { ElementRef , Injectable , OnDestroy , NgZone } from '@angular/core' ; import { ResizeObserver } from './types/resize-observer' ; import { ResizeObserverEntry } from './types/resize-observer-entry' ; import { ResizeObserverFactory } from './resize-observer.factory' ; @ Injectable ( { providedIn : 'root' } ) export class ResizeObserverService implements OnDestroy { private observer : ResizeObserver | null ; private observedElements = new WeakMap < Element , ( entry : ResizeObserverEntry ) => void > ( ) ; constructor ( private _resizeObserverFactory , private zone ) { this . observer = this . _resizeObserverFactory . create ( ( entries ) => this . handleResize ( entries ) ) ; } observe ( elementOrRef , action ) { const element = elementOrRef instanceof ElementRef ? elementOrRef . nativeElement : elementOrRef ; if ( ! this . observedElements . has ( element ) ) { if ( this . observer ) { this . zone . runOutsideAngular ( ( ) => { this . observer . observe ( element ) ; } ) ; } this . observedElements . set ( element , action ) ; } } ngOnDestroy ( ) { if ( this . observer ) { this . zone . runOutsideAngular ( ( ) => { this . observer . disconnect ( ) ; } ) ; } this . observedElements = null ; } unobserve ( elementOrRef ) { const element = elementOrRef instanceof ElementRef ? elementOrRef . nativeElement : elementOrRef ; if ( this . observedElements . has ( element ) ) { if ( this . observer ) { this . zone . runOutsideAngular ( ( ) => { this . observer . unobserve ( element ) ; } ) ; } this . observedElements . delete ( element ) ; } } private handleResize ( entries ) { entries . forEach ( ( entry ) => { const action = this . observedElements . get ( entry . target ) ; if ( action ) { action ( entry ) ; } } ) ; } }