Javascript 本机元素的大小为零
在代码中,我使用ViewChild引用了我的DOM元素。Javascript 本机元素的大小为零,javascript,angular,typescript,ionic-framework,leaflet,Javascript,Angular,Typescript,Ionic Framework,Leaflet,在代码中,我使用ViewChild引用了我的DOM元素。 但如果我尝试在ngAfterViewInit hook中检查这个元素,我会看到我的元素有offsetHeight,offsetWidth为零。(有时一切正常) 我认为这是因为我创建的元素尚未在Dom中呈现? 有什么解决办法吗? 我用的是离子4 HTML: <div id="map" #map [style.height.px] = "'300'" [style.width.px]="'100'"></div>
但如果我尝试在ngAfterViewInit hook中检查这个元素,我会看到我的元素有offsetHeight,offsetWidth为零。(有时一切正常)
我认为这是因为我创建的元素尚未在Dom中呈现?
有什么解决办法吗? 我用的是离子4
HTML:
<div id="map" #map [style.height.px] = "'300'" [style.width.px]="'100'"></div>
我希望得到高度300和宽度100。错误代码,但它可以工作
ngAfterViewInit(){
设置超时(()=>{
这个.loadMap();
}, 0);
}
您能否添加复制您的问题的提琴/片段?就您的给定而言,没有问题。@Mukyuu是的,代码段中的代码没有重现错误(这可能是因为我的应用程序更重,还是ionic 4有问题(
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);
}
...