openaire-library/dashboard/sharedComponents/page-content/page-content.component.ts

83 lines
2.2 KiB
TypeScript

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: `
<div id="page_content">
<div #header id="page_content_header">
<ng-content select="[header]"></ng-content>
</div>
<div id="page_content_inner" [ngStyle]="{'margin-top.px': (height)?height.toString():'0'}">
<ng-content select="[inner]"></ng-content>
</div>
</div>
`
})
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<number>(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();
}
}
}