【发布时间】:2017-10-20 13:47:41
【问题描述】:
我正在尝试创建一个指令,使我的布局全高。为此,我使用以下代码:
import { HostListener, Directive, ElementRef, Input, AfterViewInit } from '@angular/core';
@Directive({ selector: '[fill-height]' })
export class FillHeightDirective implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit(): void {
this.calculateAndSetElementHeight();
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.calculateAndSetElementHeight();
}
private calculateAndSetElementHeight() {
this.el.nativeElement.style.overflow = 'auto';
const windowHeight = window.innerHeight;
const elementOffsetTop = this.getElementOffsetTop();
const elementMarginBottom = this.el.nativeElement.style.marginBottom;
const footerElementMargin = this.getfooterElementMargin();
this.el.nativeElement.style.height = windowHeight - footerElementMargin - elementOffsetTop + 'px';
console.log([windowHeight, elementOffsetTop, elementMarginBottom, footerElementMargin, this.el.nativeElement.style.height]);
}
private getElementOffsetTop() {
return this.el.nativeElement.getBoundingClientRect().top;
}
private getfooterElementMargin() {
const footerElement = document.getElementById('footer');
const footerStyle = window.getComputedStyle(footerElement);
return parseInt(footerStyle.height, 10);
}
}
这很好用,但我想要一种不对页脚 ID 进行硬编码的方法。该指令将用于与页脚无关的元素,因此我不能使用@ViewChild 或@Input。我想我会创建另一个指令来获取这些信息(元素高度),它看起来像这样:
@Directive({ selector: '[footer]' })
export class NbFooterDirective implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit(): void {
this.getElementHeight();
}
@HostListener('window:resize', ['$event'])
onResize(event) {
this.getElementHeight();
}
private getElementHeight() {
return this.el.nativeElement.style.height;
}
}
现在我想要一种方法将此高度数据从该指令传递到执行计算的第一个指令。
【问题讨论】:
标签: angular typescript angular2-directives