0

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?

tomriddle_1234
  • 3,145
  • 6
  • 41
  • 71
  • the element could be invisible on page load for various reasons. Once the page has loaded the element gets its correct dimensions. – Salman A Jun 04 '19 at 09:18
  • @SalmanA, it's not hidden since !toggle2D3D is false when doing this test – tomriddle_1234 Jun 04 '19 at 09:19
  • try `console.table(element)` it will list the values of `element` at call time rather then when you toggle open objects in the developer tools console after using `console.log()` – yunzen Jun 04 '19 at 10:03

0 Answers0