我想创建一个指令,将使我的布局全高。为此,我使用下面的代码:查询DOM元素的属性角4
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;
}
}
现在我想办法从这个指令到执行的计算第一指令通过这个高度数据。
谢谢,就是我在找什么。尽管我后来诉诸于使用observables将信息从一个指令传递给另一个指令,但这对我很有用。再次感谢。 –