简体   繁体   English

如何知道图像何时以角度完全加载?

[英]How to know when an image has been fully loaded in angular?

How could I do to know when an image has been fully loaded and then show it? 我怎么能知道图像何时完全加载然后显示它? Let me explain: I'm showing an image in the following way: 让我解释一下:我用以下方式显示图像:

<img src = "www.domain.com">

but there are times it takes to load and I want to show it only when it is ready to show (100% loaded), as you might know when Is 100% loaded that image? 但有时需要加载,我想只在它准备好显示(100%加载)时显示它,你可能知道什么时候100%加载该图像? and I would like to show a loading spinner while the loading of that image is complete, I am using angular 7. 我想显示一个加载微调器,同时该图像的加载完成,我使用角度7。

There is no difference in how you would check it in Angular or in js. 在Angular或js中检查它的方式没有区别。

You need to check for img.complete flag or wait for image.onLoad event to be fired. 您需要检查img.complete标志或等待image.onLoad事件被触发。

Angular directives allow us to handle such behaviors of element, so let's create a directive: Angular指令允许我们处理元素的这种行为,所以让我们创建一个指令:

import { Directive, Output, EventEmitter, ElementRef, HostListener, OnInit } from '@angular/core';

@Directive({
  selector: 'img[loaded]'
})
export class LoadedDirective {

  @Output() loaded = new EventEmitter();

  @HostListener('load')
  onLoad() {
    this.loaded.emit();
  }

  constructor(private elRef: ElementRef<HTMLImageElement>) {
    if (this.elRef.nativeElement.complete) {
      this.loaded.emit();
    }
  }
}

Now you can catch when an image has been loaded by simple code: 现在,您可以通过简单的代码捕获图像的加载时间:

<img src="..." alt="" (loaded)="do whatever you want here">

Ng-run Example Ng-run示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM