Angular-加载图像src后的自定义指令

时间:2018-07-09 15:52:41

标签: angular angular-directive

我有问题。

在加载指令[src]后,我必须获取图像的宽度和高度。

我得到了这个html,它使用@input从父对象获取url:

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

,这里是我获取尺寸的指令:

从“ @ angular / core”导入{指令,ElementRef,AfterContentInit};

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

console.log始终显示“ 0”。加载图像后,我不知道如何启动指令过程。有谁可以帮助我吗?我在询问之前进行了搜索,但尚未找到任何答案。

谢谢! :-)

1 个答案:

答案 0 :(得分:1)

您需要使用其他生命周期挂钩来获取图像宽度。完全初始化组件视图后调用哪个。

@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);
  }
}
相关问题