当我的图像仍在从服务器加载时,如何加载占位符图像

How do I get a placeholder image to load when my image is still loading from server

我正在使用 Angular 4/ Ionic 3 构建一个应用程序,用于加载用户从服务器上传的图像。我目前正在使用下面的代码,但它不起作用:

<img src="{{user.image}} || assets/images/profileimage.png" />

我不确定我做错了什么。我认为在从服务器加载主图像之前它会显示占位符图像。相反,在主图像加载之前它仍然是空白的。我应该使用 Angular 的特定内容吗?

最好使用这个延迟加载插件。效果很棒..

安装:npm install ng2-lazyload-image --save

在 app.module.ts 中导入延迟加载:import { LazyLoadImageModule } from 'ng2-lazyload-image';

 imports: [ BrowserModule, LazyLoadImageModule ],

在你的 html 中用这个替换你的 img 标签: <img [defaultImage]="defaultImage" [lazyLoad]="image" [offset]="offset">

在你的组件中创建这个变量:

defaultImage = 'https://www.placecage.com/1000/1000';
image = 'https://images.unsplash.com/photo-1443890923422-7819ed4101c0?fm=jpg';
offset = 100;

有关更多信息,请参阅此 https://www.npmjs.com/package/ng2-lazyload-image

如果您在这方面需要任何帮助,请告诉我..

希望这对您有所帮助..

您需要在此处以字符串形式提供相对路径。

<img src="{{user.image}} || ./assets/images/profileimage.png" />

或尝试:

<img [src]="user.image || './assets/images/profileimage.png'" />
isImgLoaded:bool = false;
<img *ngIf="!isImgLoaded" src="assets/images/profileimage.png" >
<img [hidden]="!isImgLoaded" [src]="user.image" (load)="isImgLoaded = true" >

据我所知,所有现代浏览器都应该支持HTMLImageElement.complete,所以你可以直接使用

<img #userImage [src]="{{user.image}}">
<img *ngIf="!userImage.complete" src="assets/images/profileimage.png">

我找到了视频中使用的这个 YouTube video very helpful. Here is the detailed documentation for the Angular module

安装 LazyLoadImageModule

npm i ng-lazyload-image

模块文件

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LazyLoadImageModule } from 'ng-lazyload-image'; // <-- import it
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, LazyLoadImageModule], // <-- and include it
  bootstrap: [AppComponent],
})
export class MyAppModule {}

组件文件

import { Component } from '@angular/core';

@Component({
  selector: 'image',
  template: ` <img [defaultImage]="defaultImage" [lazyLoad]="image" /> `,
})
class ImageComponent {
  defaultImage = 'https://www.placecage.com/1000/1000';
  image = 'https://images.unsplash.com/photo-1443890923422-7819ed4101c0?fm=jpg';
}

其中 [defaultImage] 是占位符,[lazyLoad] 是实际图像。