gpt4 book ai didi

javascript - native 元素的大小为零

转载 作者:行者123 更新时间:2023-12-04 13:59:20 26 4
gpt4 key购买 nike

在代码中,我使用 ViewChild 引用了我的 DOM 元素。
但是如果我尝试在 ngAfterViewInit 钩子(Hook)中检查这个元素,我会看到我的元素有 offsetHeight 并且 offsetWidth 为零。(有时一切正常)
我认为那是因为我创建的元素尚未在 Dom 中呈现?
有什么解决办法吗?
我正在使用 ionic 4。

HTML:

<div id="map" #map [style.height.px] = "'300'" [style.width.px]="'100'"></div>
TS:

...
map: any;
@ViewChild('map') mapElement: ElementRef;

ngAfterViewInit() {
this.loadMap();
}

loadMap() {
//usually return 0
console.log('height:' + this.mapElement.nativeElement.offsetHeight);
console.log('width:' + this.mapElement.nativeElement.offsetWidth);

this.map = DG.map(this.mapElement.nativeElement);
}
...

我希望得到高度 300 和宽度 100。

最佳答案

错误的代码,但它有效

ngAfterViewInit() {
setTimeout(() => {
this.loadMap();
}, 0);
}

关于javascript - native 元素的大小为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com