元素的宽度和高度始终返回0,但console.log(element)的属性显示为正常,呈现的属性为

时间:2019-06-04 09:15:42

标签: html css angular ionic-framework

我在Angular 7和ViewChild上使用了Ionic 4。

<ion-content>
    <ion-grid>
        <ion-row>
            <ion-col>
                <div [hidden]="!toggle2D3D" id="zrenderCanvas" #zrenderCanvas></div>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>

喜欢,

#zrenderCanvas {
  display: block;
  width: 100%;
  height  : 100%;
  touch-action: none;
}

类似的代码

@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???
...
}

更新:

我通过引用https://stackoverflow.com/a/294273/921082MutationObserver: How to observe mutations in width/height of flex child?https://stackoverflow.com/a/51173985/921082部分解决了该问题。这是有角度的zone.js,使视图初始化花费的时间比预期的长。我用setTimeout(,0)包围了获取宽度线,这使语句在zone.js之后运行,然后得到正确的值。但是,通过执行setTimeout,setTimeout函数中的我的rxjs订阅行之一停止工作。所以我想说它已经部分解决了。有更好的主意吗?

0 个答案:

没有答案