我正在尝试创建一个指令,使我的布局全高。为此,我使用以下代码:
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;
}
}
现在我想要一种方法将此高度数据从此指令传递给执行计算的第一个指令。
答案 0 :(得分:1)
首先,this.el.nativeElement.style
是样式属性,而不是计算样式。如果你想获得计算样式,请使用'window.getComputedStyle'位用于高度的情况,如果高度将是例如auto
,它将只给出一个字符串'auto'
。因此,如果您想要真正的计算高度,请使用this.el.nativeElement.offsetHeight
或this.el.nativeElement.clientHeight
。请看一下这个答案:offsetHeight vs clienHeight。
我已经为我的问题解决方案创建了一个示例。所以请按照plunker link查看代码。
基本概念是你应该在第一个组件上有一个输出并从第二个组件中听取它。