【发布时间】:2019-06-28 19:29:50
【问题描述】:
在代码中,我使用 ViewChild 引用了我的 DOM 元素。
但是,如果我尝试在 ngAfterViewInit 挂钩中检查此元素,我会看到我的元素具有 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。
【问题讨论】:
-
你能添加 fiddle/sn-p 来重现你的问题吗?就您的code 而言,没有问题。
-
@Mukyuu 是的,sn-p 中的代码不会重现错误(这可能是因为我的应用程序更重,或者 ionic 4 有问题(
标签: javascript angular typescript ionic-framework leaflet