首页 > 解决方案 > 如何在 Angular 中获取图像的真实大小并调整大小?

问题描述

有一张图:

@ViewChild('image')
readonly image: ElementRef;

html:

 <img #image class="image" />

CSS自动调整后如何获得实际大小(宽度,高度)和调整大小?

我试过这个:

  console.log(this.container.nativeElement.clientHeight);
  console.log(this.container.nativeElement.clientWidth);

它返回我 500 和 0。

标签: javascriptangular

解决方案


尝试这个 :

<img #image src="images/path" class="image" (load)="onLoad()" />

在控制器中

onLoad() {
  console.log((this.image.nativeElement as HTMLImageElement).width);
  console.log((this.image.nativeElement as HTMLImageElement).height);
}

演示:https ://stackblitz.com/edit/angular-rqceml?file=src/app/app.component.ts


推荐阅读