Tạo thành phần hiển thị hình ảnh trình giữ chỗ cho đến khi hình ảnh được yêu cầu được tải và ẩn hình ảnh được yêu cầu. Khi hình ảnh được tải, bạn ẩn trình giữ chỗ và hiển thị hình ảnh.
@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;
}
Xem nó hoạt động trong Plunker.
Cập nhật
Bây giờ tôi hiểu các yêu cầu tốt hơn, đây là một giải pháp với hình nền. Đó là một chút hacky, và tôi thích một bản gốc tốt hơn ...
@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;
}
}
Updated plunker.
có thể trùng lặp của [Ionic 2: (Lazy) Loading spinner cho hình ảnh] (http://stackoverflow.com/ câu hỏi/38846271/ionic-2-lazy-loading-spinner-for-pictures) –