通过自定义指令可以使用解决了,上代码指令内容error-img.directive.ts import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({ selector: '[appErrorImg]'})export class ErrorImgDirective { // tslint:disable-next-line:no-input-rename @Input('appErrorImg') errorImagSrc: string; constructor(public elementRef: ElementRef) { } @HostListener('error', ['$event.target']) ImageError(event) { if (this.errorImagSrc) { event.src = this.errorImagSrc; } else { // tslint:disable-next-line:max-line-length event.src = 'https://ss1.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=96baa30f1bdfa9ece22e501752d0f754/342ac65c103853439f9b46329913b07eca808849.jpg'; } }}使用方法:如果传值则使用值的图片,否则使用指令内默认图pain <img [src]='product?.goodsImg' appErrorImg> <!-- <img src="../../../assets/images/404icon.png" > --> <div class="activity-info" *ngIf="showActive||product?.is_act"> <img [src]="product?.act_img" appErrorImg="https://ss3.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=f98266a88dd6277ff612343818391f63/1b4c510fd9f9d72a1edae20ede2a2834349bbb63.jpg"> </div>
<img [src]="yourImgPath" onError="this.src='yourErrorDefaultImg' ">.第一个属性[src]是你要显示的图片的路径,第二个属性onError是图片不存在是显示的默认图片
通过自定义指令可以使用解决了,上代码
指令内容error-img.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appErrorImg]'
})
export class ErrorImgDirective {
// tslint:disable-next-line:no-input-rename
@Input('appErrorImg') errorImagSrc: string;
constructor(public elementRef: ElementRef) { }
@HostListener('error', ['$event.target'])
ImageError(event) {
}
}
使用方法:
如果传值则使用值的图片,否则使用指令内默认图pain
<img [src]='product?.goodsImg' appErrorImg>