0
votes

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

1 Answers

1
votes

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);
  }
}