You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12 实现图片加载完成后显示、加载阶段展示骨架屏的问题

问题根因

你写的代码存在几个明显问题导致效果不符合预期:

  • ngx-skeleton-loader的theme配置里borderradius拼写错误,应该是border-radius,导致自定义圆角不生效
  • 用[hidden]控制图片显示不可靠:hidden是原生属性,优先级低于css类样式,如果你的img类中包含display相关属性(比如你用到的bootstrap工具类可能自带display规则),会直接覆盖hidden的隐藏效果
  • 你现在的代码里src是硬编码的本地静态地址,如果你是从服务端API动态拉取图片地址,需要等接口返回src后再渲染img标签,否则img会先加载无效地址提前触发load事件,导致骨架屏提前消失
  • 如果是分区块多图渲染的场景,单个imgLoad变量会导致所有区块的状态互相影响,一个图片加载完所有骨架屏都会消失

修正代码

单图场景

HTML

<div class="col-12 p-0">
  <ngx-skeleton-loader 
    *ngIf="!imgLoad" 
    count="1" 
    [theme]="{
      'border-radius':'7px', 
      'background-color': '#ccc',
      'margin-top':'0', 
      'min-height': '25vh',
      'width':'100%' 
    }">
  </ngx-skeleton-loader>
  <img 
    *ngIf="imgSrc"
    (load)="loadImage()" 
    (error)="loadImage()"
    [hidden]="!imgLoad"
    [src]="imgSrc" 
    alt="" 
    class="w-100 h-auto image-border"
  >
</div>

TS

imgLoad: boolean = false;
// 存储服务端返回的图片地址
imgSrc: string = '';

// 调用服务端API获取图片地址的逻辑
fetchImageSrc() {
  // 替换为你的实际接口请求代码
  this.yourApiService.getImgUrl().subscribe(res => {
    this.imgSrc = res.data.url;
  })
}

loadImage() {
  this.imgLoad = true;
}

多区块多图场景

如果是多个分区块独立渲染图片,用数组存储每个图片的独立状态:

HTML

<div class="col-12 p-0" *ngFor="let imgItem of imgList; let index = index">
  <ngx-skeleton-loader 
    *ngIf="!imgItem.isLoaded" 
    count="1" 
    [theme]="{
      'border-radius':'7px', 
      'background-color': '#ccc',
      'margin-top':'0', 
      'min-height': '25vh',
      'width':'100%' 
    }">
  </ngx-skeleton-loader>
  <img 
    *ngIf="imgItem.src"
    (load)="loadImgByIndex(index)" 
    (error)="loadImgByIndex(index)"
    [src]="imgItem.src" 
    alt="" 
    class="w-100 h-auto image-border"
    [hidden]="!imgItem.isLoaded"
  >
</div>

TS

// 存储所有图片的地址和加载状态
imgList: {src: string, isLoaded: boolean}[] = [];

fetchImgList() {
  // 替换为实际接口请求
  this.yourApiService.getImgList().subscribe(res => {
    this.imgList = res.data.map(item => ({
      src: item.url,
      isLoaded: false
    }))
  })
}

loadImgByIndex(index: number) {
  this.imgList[index].isLoaded = true;
}

内容的提问来源于stack exchange,提问作者Ab2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:06:05