【问题标题】:ngFor using index to indentify itemsngFor 使用索引来识别项目
【发布时间】:2016-11-03 17:00:37
【问题描述】:

我有以下 ngFor 正在显示图像。如果缺少图像(Http 404),我只想隐藏 img 元素。问题是 imgMissing 变量对于所有元素都是全局的。我们可以通过组件文件中的逻辑或通过为项目部分指定单独的组件文件来轻松解决此问题。

但是是否可以仅在模板中解决这个问题,例如通过使用索引来识别丢失的图像项?

<div *ngFor="let item of items; let i = index">
    <img *ngIf="!imgMissing" [src]="item.imgSrc" (error)="imgMissing=true;" />
</div>

【问题讨论】:

  • 图片是否丢失的定义是什么?否则,如果您知道缺少的索引,*ngIf="i != knownIndex" 或者如果 imgSrc 为空白(缺少)*ngIf="item.imgSrc"
  • @silentsod 感谢您的回复。我忘了提到我不知道丢失的索引,我在尝试获取图像时只收到 404 错误。

标签: angular


【解决方案1】:

只需使用本机 onerror 处理程序来设置样式。

<div *ngFor="let item of items; let i = index">
    <img [src]="item.imgSrc" onerror="this.style.display='none'" />
</div>

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2019-08-28
    • 2018-01-09
    • 2011-06-17
    相关资源
    最近更新 更多