【发布时间】: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') 的情况下实现这一点?
【问题讨论】:
-
这不起作用的原因是 structural directives like
*ngIfact as template boundaries for template variables 并且您无法访问声明边界之外的模板变量,除非(正如您的问题指出的那样)您添加@VeiwChild引用它。见:Access template variable in *ngIf -
有道理,谢谢@DM。
标签: angular