我需要知道如何使用 Angular 仅在客户端检测图像是否存在。我听说我们可以通过超时功能设置默认图像,但我不知道如何捕获 404 错误。
我只需要在 getResourceImg() 上编写代码,因为 angular's style guide says
resource-ui.component.ts
@Input() resource: IResourcePublished;
// ...
resourceImgUrlLogoDefault: string = 'assets/images/logo_default.png';
resourceImgUrl: string;
constructor(private modalService: NgbModal) {}
ngOnInit(): void {
this.resourceImgUrl = this.getRessourceImg(this.resource);
}
getResourceImg(resource: IResourcePublished): string {
return 'assets/images/screen-resources/' + resource.id + '.png';
}
//..
这是模板(使用 *ngFor="let resource of resources"
生成):
resource-ui.component.html
<div class="card" [style.background]="categoryColor">
<div class="card-header" ngbTooltip="More infos" (click)="openResourceDetails()">
<img
class="layout-img img-fluid"
[src]="resourceImgUrl"
alt="resource-{{resource.id}}"
/>
</div>
<!-- ... -->
</div>
最佳答案
您可以创建可重复使用的指令,例如:
fallback-img.directive.ts
import { Directive, Input, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: 'img[fallback]'
})
export class FallbackImgDirective {
@Input()
@HostBinding('src')
src: string;
@Input() fallback: string;
@HostListener('error')
onError() {
this.src = this.fallback;
}
}
用法
<img src="http://unknown/404.jpg" fallback="https://via.placeholder.com/150" alt="">
关于Angular 10 - 检测图像是否仅存在于客户端,否则为默认图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63227480/