2017-10-20 135 views
1

我想创建一个指令,将使我的布局全高。为此,我使用下面的代码:查询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; 
    } 
} 

现在我想办法从这个指令到执行的计算第一指令通过这个高度数据。

回答

1

首先,this.el.nativeElement.style是风格属性而不是计算风格。如果你想获得计算样式,那么如果高度为例如auto,那么使用'window.getComputedStyle'位作为高度的情况,它将仅给出字符串'auto'。所以如果你想要真正的计算高度使用this.el.nativeElement.offsetHeightthis.el.nativeElement.clientHeight。看看这个答案更多:offsetHeight vs clienHeight

我已经为我的问题解决方案创建了一个示例。所以请按照plunker link并查看代码。

其基本概念是,您应该在第一个组件上有输出,并从第二个组件收听。

+0

谢谢,就是我在找什么。尽管我后来诉诸于使用observables将信息从一个指令传递给另一个指令,但这对我很有用。再次感谢。 –

相关问题