app/@overflow/commons/ui/directive/auto-height.directive.ts
2018-09-21 18:28:34 +09:00

62 lines
1.7 KiB
TypeScript

// https://github.com/arthurvaverko/ngx-fill-height/tree/master/src/app/fill-height
import { Directive, AfterViewInit, Input, HostListener, ElementRef, ChangeDetectorRef, OnInit, OnDestroy } from '@angular/core';
@Directive({
selector: '[of-auto-height]'
})
export class AutoHeightDirective implements OnInit, OnDestroy, AfterViewInit {
@Input() footerElement = null;
@HostListener('window:resize', ['$event'])
onResize(event) {
this.calculateAndSetElementHeight();
}
constructor(
private elementRef: ElementRef,
private changeDetector: ChangeDetectorRef,
) {
}
ngOnInit(): void {
}
ngAfterViewInit(): void {
this.calculateAndSetElementHeight();
}
ngOnDestroy(): void {
}
/**
* forceCalculate
*/
public forceCalculate() {
this.calculateAndSetElementHeight();
}
private calculateAndSetElementHeight() {
this.changeDetector.detectChanges();
this.elementRef.nativeElement.style.overflow = 'auto';
const windowHeight = window.innerHeight;
const elementOffsetTop = this.getElementOffsetTop();
const elementMarginBottom = this.elementRef.nativeElement.style.marginBottom;
const footerElementMargin = this.getfooterElementMargin();
this.elementRef.nativeElement.style.height = windowHeight - footerElementMargin - elementOffsetTop + 'px';
console.log([windowHeight, elementOffsetTop, elementMarginBottom, footerElementMargin, this.elementRef.nativeElement.style.height]);
}
private getElementOffsetTop() {
return this.elementRef.nativeElement.getBoundingClientRect().top;
}
private getfooterElementMargin() {
if (!this.footerElement) { return 0; }
const footerStyle = window.getComputedStyle(this.footerElement);
return parseInt(footerStyle.height, 10);
}
}