我有一个Angular指令,用于以惰性方式加载图像。代码如下:
import { Directive, ElementRef } from '@angular/core';
@Directive({ selector: '[appImgLazy]' })
export class LazyLoadingImgDirective {
constructor({ nativeElement }: ElementRef<HTMLImageElement>) {
const supports = 'loading' in HTMLImageElement.prototype;
if (supports) {
nativeElement.setAttribute('loading', 'lazy');
}
}
}
我想在加载实际图像时显示一个占位符图像,完成后,将占位符替换为实际图像。我已经尝试过this answer中建议的方法,但无法正常工作。如果我使用Chrome DevTools检查网络流量,尽管它已经加载,但似乎每次都在请求图像。而且,占位符从不显示。
带有修改的完整指令:
import {
Directive,
Attribute,
Renderer2,
ElementRef,
HostListener } from '@angular/core';
@Directive({
selector: '[appImgLazy]'
})
export class LazyLoadingImgDirective {
constructor(
@Attribute('loader') public loader: string,
@Attribute('onErrorSrc') public onErrorSrc: string,
private renderer: Renderer2,
private el: ElementRef,
{ nativeElement }: ElementRef<HTMLImageElement>) {
const supports = 'loading' in HTMLImageElement.prototype;
if (supports) {
nativeElement.setAttribute('loading', 'lazy');
}
this.renderer.setAttribute(this.el.nativeElement, 'src', this.loader);
}
@HostListener('load') onLoad() {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.el.nativeElement.src);
}
@HostListener('error') onError() {
this.renderer.setAttribute(this.el.nativeElement, 'src', this.onErrorSrc);
}
}
用法:
<img
appImgLazy
onErrorSrc="src/assets/images/not-found-image.png"
loader="src/assets/images/placeholder.png"
[src]="product.cover">
我的package.json
依赖项:
"dependencies": {
"@angular/animations": "~9.1.6",
"@angular/cdk": "^9.2.3",
"@angular/common": "~9.1.6",
"@angular/compiler": "~9.1.6",
"@angular/core": "~9.1.6",
"@angular/forms": "~9.1.6",
"@angular/localize": "^9.1.12",
"@angular/platform-browser": "~9.1.6",
"@angular/platform-browser-dynamic": "~9.1.6",
"@angular/router": "~9.1.6",
"@ngx-translate/core": "^12.1.1",
"@ngx-translate/http-loader": "^4.0.0",
"bootstrap": "^4.4.1",
"cookieconsent": "^3.1.1",
"messageformat": "^2.3.0",
"ngx-cookieconsent": "^2.2.3",
"ngx-device-detector": "^1.4.5",
"ngx-toastr": "^12.0.1",
"ngx-translate-messageformat-compiler": "^4.7.0",
"rxjs": "~6.5.4",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
},