import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, HostListener, OnDestroy, ViewChild } from "@angular/core"; import {Observable, Subscription} from "rxjs"; import {distinctUntilChanged} from "rxjs/operators"; @Component({ selector: '[page-content]', template: `
` }) export class PageContentComponent implements OnDestroy, AfterViewInit{ public height = 0; private subscription: Subscription; @ViewChild('header') header: ElementRef; constructor(private cdr: ChangeDetectorRef) { } @HostListener('window:resize', ['$event']) onResize(event) { this.height = this.getHeight(); this.cdr.detectChanges(); } getHeight(): number{ return this.header.nativeElement.offsetHeight; } setupHeightMutationObserver() { if (typeof document !== 'undefined') { const observable = new Observable(observer => { const callback = (mutationsList, observer2) => { observer.next(this.getHeight()); }; // Create an observer instance linked to the callback function const elementObserver = new MutationObserver(callback); // Options for the observer (which mutations to observe) const config = {attributes: true, attributeFilter: ['class'], childList: true, subtree: true}; // Start observing the target node for configured mutations elementObserver.observe(this.header.nativeElement, config); }); this.subscription = observable .pipe( distinctUntilChanged()//if the value hasn't changed, don't continue ) .subscribe(newHeight => { this.height = this.getHeight(); this.cdr.detectChanges(); }); } } ngAfterViewInit() { this.setupHeightMutationObserver(); this.height = this.getHeight(); this.cdr.detectChanges(); } ngOnDestroy() { if(this.subscription) { this.subscription.unsubscribe(); } } }