0

我需要知道渲染元素的高度。我不在乎元素是否报告它或父项是否检测到高度。

我一直在研究这个问题,我的第一个根本原因是 :host 元素必须有它的display:block集合,我已经做到了。(我做得对吗?)

this.nativeElement将重要信息转储到 console.log 但是当我尝试以编程方式访问该值时,它出现“0”。

文件:

img-fader.component.html

<img [src]='imgSrc' class="item carousel-item" style="width: 100%; display: block;"/>

img-fader.component.css

:host {
    display: block;
}

img.carousel-item {
    position: absolute;
    left: 0;
}

img-fader.component.ts(重要部分)

export class ImgFaderComponent implements AfterViewInit {
  @ContentChildren(ImgFaderComponent, {read: ElementRef}) imgList: QueryList<ElementRef>;

  constructor() {}

  ngAfterViewInit() {
    this.imgList.forEach(img => console.log('Img: ', img.nativeElement.children[0].offsetHeight));
  }
}
4

1 回答 1

0

如果有人仍在为图像 offsetHeight 的类似问题而苦苦挣扎,我发现如果您使用setTimeout函数包装命令以获取 offsetHeight ,那么您就可以正确获得图像高度(和我想的宽度)。

发生这种情况是因为异步命令运行到下一个周期,所以图像已经加载。

于 2020-08-16T00:37:34.637 回答