【问题标题】:Angular - custom directive after image src loadedAngular - 加载图像 src 后的自定义指令
【发布时间】:2018-12-17 08:56:46
【问题描述】:

我有一个问题。

使用指令 [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”。我不知道如何在加载图像后启动指令过程。有人能帮助我吗?我在问之前搜索过,但我还没有找到任何答案。

谢谢! :-)

【问题讨论】:

    标签: angular angular-directive


    【解决方案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);
      }
    }
    

    【讨论】:

    • 以这种方式,并非在所有情况下我都在 ngAfterViewInit 之前获得了图像尺寸。从 30 个 img 元素的列表中,几乎有一半得到了大小
    • 你在循环图像列表吗?
    • 正确。父组件创建一个托管我的 img 的组件列表
    • 在 app-daily-update-box 我得到了我需要的图片来获得尺寸
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多