首页 文章

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

提问于
浏览
0

我有一个问题 .

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

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

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

在这里我获得尺寸的指令:

从'@ angular / core'导入{Directive,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 回答

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

相关问题