【发布时间】:2018-05-04 06:02:49
【问题描述】:
我有一个演示 Here
我在一个组件中有一个 div,它用 *ngIf 显示
我需要知道这个元素的高度。
我似乎无法在它显示之前或在显示元素的函数中执行此操作。
是否发生了我可以用来获取高度的事件
import { Component, Input, ElementRef, OnInit, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'child-comp',
templateUrl: './child.component.html'
})
export class ChildComponent implements OnInit, AfterViewInit {
@Input() parent: ElementRef;
private block: ElementRef;
@ViewChild('block') set content(content: ElementRef) {
this.block = content;
}
show: boolean = false
blockHeight: number
constructor(){ }
// ngOnInit(){
// this.blockHeight = this.block.nativeElement.clientHeight;
// }
ngAfterViewInit(){
this.blockHeight = this.block.nativeElement.clientHeight;
console.log('AfterViewInit '+this.blockHeight);
}
showBlock(){
this.show = !this.show
this.blockHeight = this.block.nativeElement.clientHeight;
console.log('showBlock '+this.blockHeight);
}
}
【问题讨论】:
-
在使用 ngIf 显示之前,您无法获取高度(它根本不存在)。
-
那么有什么方法可以知道它何时在那里,然后在它可用时立即捕获高度
标签: angular