angular2 onError图像绑定

jcd*_*dsr 12 typescript angular

我想知道我们是否可以使用angular2绑定或插入图像标签上的onError,

在app.component.ts上:

imageUrl:string;

  constructor( ) {
      this.imageUrl = 'graphics/placeholder.gif';
   }
Run Code Online (Sandbox Code Playgroud)

在app.component.html上:

<img class="img-responsive" [src]="'graphics/image-1.jpg'" onError="imageUrl"/>
Run Code Online (Sandbox Code Playgroud)

以下方法有效.

<img class="img-responsive" [src]="'graphics/image-1.jpg'" onError="this.src='graphics/placeholder.gif'"/>
Run Code Online (Sandbox Code Playgroud)

但是,当我们在应用程序上使用许多图像时,我想将其作为一个简单的动态解决方案,我也找到了这个答案,

Angular 2 - 检查图像URL是有效还是损坏

但由于某种原因不起作用,我不知道我在这里做错了什么

Ame*_*ani 17

它几乎完成了他只是忘了在事件发生后改变图像.

errorHandler(event) {
   console.debug(event);
   event.target.src = "https://cdn.browshot.com/static/images/not-found.png";
}
Run Code Online (Sandbox Code Playgroud)

这是 链接


Sau*_*47g 12

component.ts

onImgError(event){
 event.target.src = './assets/imgs/altImg.png'
//Do other stuff with the event.target
}
Run Code Online (Sandbox Code Playgroud)

component.html

 <img [src]="imgUrl" (error)="onImgError($event)">
Run Code Online (Sandbox Code Playgroud)