更新时间:2023-12-05 16:58:46
创建一个组件,在加载请求的图像之前显示占位符图像,并隐藏请求的图像.加载图像后,隐藏占位符并显示图像.
Create a component that shows the placeholder image until the requested image is loaded, and hides the requested image. Once the image is loaded, you hide the placeholder and show the image.
@Component({
selector: 'image-loader',
template: `<img *ngIf="!loaded" src="url-to-your-placeholder"/>
<img [hidden]="!loaded" (load)="loaded = true" [src]="src"/>`
})
export class ImageLoader {
@Input() src;
}
查看它在 Plunker 中的工作.
See it working in Plunker.
更新
现在我更好地理解了要求,这里有一个带有背景图片的解决方案.有点hacky,我更喜欢原来的...
Now that I understand the requirements better, here's a solution with background image. It's a little hacky, and I like the original one better...
@Directive({
selector: '[imageLoader]'
})
export class ImageLoader {
@Input() imageLoader;
constructor(private el:ElementRef) {
this.el = el.nativeElement;
this.el.style.backgroundImage = "url(http://smallenvelop.com/demo/image-loading/spinner.gif)";
}
ngOnInit() {
let image = new Image();
image.addEventListener('load', () => {
this.el.style.backgroundImage = `url(${this.imageLoader})`;
});
image.src = this.imageLoader;
}
}
更新插件.