0

i've got a problem.

I have to get width and height of an image after loaded with the directive [src].

I got this html that get he url from a parent object with @input:

<img fitImageSize [src]="content.openGraphImage.contentUrl"/>

and here my directive to get the dimensions:

import { Directive, ElementRef, AfterContentInit } from '@angular/core';

@Directive({
  selector: '[fitImageSize]'
})
export class FitImageSizeDirective implements AfterContentInit {

  el: ElementRef
  private imgWidth: any;
  private imgHeight: any;

  constructor(_el:ElementRef) {
    this.el = _el;
  }

  ngAfterContentInit() {
    this.imgWidth = this.el.nativeElement.offsetWidth;
    this.imgHeight = this.el.nativeElement.offsetHeight;    
    console.log(this.imgWidth);
  }
}

The console.log always print "0". I don't know how to launch the directive process after the image is loaded. Can someone help me please? I searched before asking but i haven't found any answers yet.

Thanks! :-)

1 Answer 1

1

You need to Use different lifecycle hook to get the image width. Which called after the components view has been full initialized.

@Directive({
  selector: '[fitImageSize]'
})
export class FitImageSizeDirective implements AfterViewInit {

  el: ElementRef
  private imgWidth: any;
  private imgHeight: any;

  constructor(_el:ElementRef) {
    this.el = _el;
  }

  ngAfterViewInit() {
    this.imgWidth = this.el.nativeElement.offsetWidth;
    this.imgHeight = this.el.nativeElement.offsetHeight;    
    console.log(this.imgWidth);
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

In this way not in every case i got the image dimension before the ngAfterViewInit. From a list of 30 img elements almost the half get the size
are you looping the image list?
Correct. The parent component creates a list of components hosting my img
<div class="col-12 col-sm-6 col-md-4 col-lg-3" *ngFor="let content of contents; trackBy:index"> <app-daily-update-box [content]="content"></app-daily-update-box> </div>
in app-daily-update-box I got the images that I need to get the size
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.