1
|
import {
|
2
|
AfterViewInit,
|
3
|
ChangeDetectorRef,
|
4
|
Component,
|
5
|
ElementRef,
|
6
|
HostListener,
|
7
|
OnDestroy,
|
8
|
ViewChild
|
9
|
} from "@angular/core";
|
10
|
import {Observable, Subscription} from "rxjs";
|
11
|
import {distinctUntilChanged} from "rxjs/operators";
|
12
|
|
13
|
@Component({
|
14
|
selector: '[page-content]',
|
15
|
template: `
|
16
|
<div id="page_content">
|
17
|
<div #header id="page_content_header">
|
18
|
<ng-content select="[header]"></ng-content>
|
19
|
</div>
|
20
|
<div id="page_content_inner" [ngStyle]="{'margin-top.px': (height)?height.toString():'0'}">
|
21
|
<ng-content select="[inner]"></ng-content>
|
22
|
</div>
|
23
|
</div>
|
24
|
`
|
25
|
})
|
26
|
export class PageContentComponent implements OnDestroy, AfterViewInit{
|
27
|
public height = 0;
|
28
|
private subscription: Subscription;
|
29
|
@ViewChild('header') header: ElementRef;
|
30
|
|
31
|
constructor(private cdr: ChangeDetectorRef) {
|
32
|
}
|
33
|
|
34
|
@HostListener('window:resize', ['$event'])
|
35
|
onResize(event) {
|
36
|
this.height = this.getHeight();
|
37
|
this.cdr.detectChanges();
|
38
|
}
|
39
|
|
40
|
getHeight(): number{
|
41
|
return this.header.nativeElement.offsetHeight;
|
42
|
}
|
43
|
|
44
|
setupHeightMutationObserver() {
|
45
|
if (typeof document !== 'undefined') {
|
46
|
const observable = new Observable<number>(observer => {
|
47
|
const callback = (mutationsList, observer2) => {
|
48
|
observer.next(this.getHeight());
|
49
|
};
|
50
|
|
51
|
// Create an observer instance linked to the callback function
|
52
|
const elementObserver = new MutationObserver(callback);
|
53
|
|
54
|
// Options for the observer (which mutations to observe)
|
55
|
const config = {attributes: true, attributeFilter: ['class'], childList: true, subtree: true};
|
56
|
// Start observing the target node for configured mutations
|
57
|
elementObserver.observe(this.header.nativeElement, config);
|
58
|
});
|
59
|
|
60
|
this.subscription = observable
|
61
|
.pipe(
|
62
|
distinctUntilChanged()//if the value hasn't changed, don't continue
|
63
|
)
|
64
|
.subscribe(newHeight => {
|
65
|
this.height = this.getHeight();
|
66
|
this.cdr.detectChanges();
|
67
|
});
|
68
|
}
|
69
|
}
|
70
|
|
71
|
ngAfterViewInit() {
|
72
|
this.setupHeightMutationObserver();
|
73
|
this.height = this.getHeight();
|
74
|
this.cdr.detectChanges();
|
75
|
}
|
76
|
|
77
|
ngOnDestroy() {
|
78
|
if(this.subscription) {
|
79
|
this.subscription.unsubscribe();
|
80
|
}
|
81
|
}
|
82
|
}
|