0

I've an image element like this:

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

I intend to print the dimensions of the image right below it, like

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

However I get the error:

Property 'imgElement' does not exist on type MyComponent.

Is there a way to achieve this without having a @ViewChild('imgElement') in the component?

D M
  • 5,769
  • 4
  • 12
  • 27
Sanjay Verma
  • 1,390
  • 22
  • 40
  • 1
    The reason this does not work is that [structural directives like `*ngIf` act as template boundaries for template variables](https://angular.io/guide/template-reference-variables#template-variable-scope) and you cannot access a template variable outside of the boundary it was declared in unless (as your question points out) you add a `@VeiwChild` reference to it. See: [Access template variable in *ngIf](https://stackoverflow.com/questions/45247462/access-template-variable-in-ngif) – D M Dec 30 '21 at 22:22
  • Makes sense, thank you @DM. – Sanjay Verma Dec 30 '21 at 23:22

1 Answers1

1

The issue is the *ngIf part. Without that the element is directly referenceable.

i.e.

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

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

Edit:

As @DM mentioned, a good solution is to wrap the whole block in an *ngIf, e.g.,

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

  {{imgElement.naturalWidth}} x {{imgElement.naturalHeight}}
</ng-container>
Sanjay Verma
  • 1,390
  • 22
  • 40