1

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

dota2pro
  • 7,220
  • 7
  • 44
  • 79

2 Answers2

2

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.

Andrew Allen
  • 6,512
  • 5
  • 30
  • 73
2

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)">
Alexandr Mihalciuc
  • 2,537
  • 15
  • 12