Reputation: 7874
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
Upvotes: 1
Views: 1189
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
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