【问题标题】:Reference an element without ViewChild, directly in an Angular HTML template直接在 Angular HTML 模板中引用没有 ViewChild 的元素
【发布时间】:2021-12-30 20:46:11
【问题描述】:

我有一个像这样的图像元素:

<img #imgElement *ngIf="data.image" [src]="data.image" width=200 />

我打算在其正下方打印图像的尺寸,例如

{{imgElement.naturalWidth}} x {{imgElement.naturalHeight}}

但是我得到了错误:

类型 MyComponent 上不存在属性“imgElement”。

有没有办法在组件中不包含@ViewChild('imgElement') 的情况下实现这一点?

【问题讨论】:

标签: angular


【解决方案1】:

问题在于*ngIf 部分。没有那个元素是直接可引用的。

<img #imgElement [src]="data.image" width=200 />

{{imgElement.naturalWidth}} x {{imgElement.naturalHeight}}

编辑:

正如@DM 提到的,一个好的解决方案是将整个块包装在*ngIf 中,例如,

<ng-container *ngIf="data.image">
  <img #imgElement [src]="data.image" width=200 />

  {{imgElement.naturalWidth}} x {{imgElement.naturalHeight}}
</ng-container>

【讨论】:

  • 是的,就是这样。
  • 您可能希望将整个块包装在 &lt;ng-container *ngIf="data.image"&gt;&lt;/ng-container&gt; 中,以便在加载图像之前不显示值。
  • 很好的建议,谢谢@DM!!
猜你喜欢
  • 1970-01-01
  • 2012-07-04
  • 2022-07-19
  • 2019-06-25
  • 1970-01-01
  • 2020-06-13
  • 2019-12-30
  • 1970-01-01
  • 2017-12-04
相关资源
最近更新 更多