dota2pro
dota2pro

Reputation: 7874

How to get Image width / height if the image is too big in Angular?

When I try to log image width in ngAfterViewInit method

I get width = 0 Since the image is too Big

How can I properly see the image width without using a setTimeout()

Here is the code example

PS. I tried the solution in this post but was unsuccessful

This is what i see

enter image description here

Upvotes: 1

Views: 1189

Answers (2)

Andrew Allen
Andrew Allen

Reputation: 8062

Per answer here Detect when image has loaded in img tag hook into load event

import { Component, Input, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
  <img #hdImage
  src="https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg"
  (load)="dosomething(hdImage.width)">
  `,
  styles: [``]
})
export class HelloComponent {
  @ViewChild('hdImage', { static: false }) HdImage: ElementRef;
  img: HTMLImageElement;

  dosomething(width: number) {
    console.log('[dosomething] width', width);
  }

}

@AlexandrMihalciuc answer is better as it is better to pass the width directly so I've stolen it to improve this now accepted answer.

Upvotes: 2

Alexandr Mihalciuc
Alexandr Mihalciuc

Reputation: 2577

Subscrive to load event of the img tag:

 <img #hdImage      src="https://upload.wikimedia.org/wikipedia/commons/f/ff/Pizigani_1367_Chart_10MB.jpg" (load)="loaded(hdImage.width)">

Upvotes: 2

Related Questions