I was using Ionic 4 with Angular 7, with ViewChild.
<ion-content>
<ion-grid>
<ion-row>
<ion-col>
<div [hidden]="!toggle2D3D" id="zrenderCanvas" #zrenderCanvas></div>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
scss like,
#zrenderCanvas {
display: block;
width: 100%;
height : 100%;
touch-action: none;
}
code like,
@ViewChild('zrenderCanvas', {read: ElementRef}) zrenderCanvas: ElementRef;
private zrele: any;
...
ngAfterViewInit() {
// viewchild only works after view inited !
this.zrele = this.zrenderCanvas.nativeElement;
this.cdRef.detectChanges();
console.log(this.zrele.offsetWidth); // this returns 0
console.log(document.getElementById('zrenderCanvas').offsetWidth); // this return 0 too
console.log(this.zrele); // however this show the object has a offsetWidth attribute, and it's not 0 !!! Why???
...
}
Update:
I partially solved the issue by reference https://stackoverflow.com/a/294273/921082 and MutationObserver: How to observe mutations in width/height of flex child? and https://stackoverflow.com/a/51173985/921082. It is the angular zone.js make the view init take longer than expected. I surround the get width line with setTimeout(,0), which make the statements run after zone.js, then I got the correct value. However by doing the setTimeout, one of my rxjs subscribe line inside the setTimeout function stops working. So I'd say it's partially solved. Any better idea?