环境:
"@angular/core": "11.2.7",
"@ionic/angular": "^5.4.0",
问题:
在组件里需要获取到document.body.clientWidth的值
diameter = Math.round((this.elementRef.nativeElement.clientWidth || this.elementRef.nativeElement.offsetWidth || document.body.clientWidth || document.body.offsetWidth) * 0.75);
这个时候拿到的值为0。 在ngAfterViewInit里仍然拿不到。
解决方案:
在ionic的生命周期里再拿,
ionViewDidEnter(){
this.diameter = Math.round((this.elementRef.nativeElement.clientWidth || this.elementRef.nativeElement.offsetWidth || document.body.clientWidth || document.body.offsetWidth) * 0.75);
}
这个时候就可以拿到了
问题原因:
ionic路由中间有动画,所以会在angular组件加载后之后有一段时间来加载动画,所以在angular的生命周期里拿不到dom的宽高,而当Iocnic页面加载完毕后就可以拿到了