2

I have an Angular 9 application. I need to display alternative image if the one specified in src is missing. I don't want use onerror, because it is deprecated.

Here is what I found:

<div *ngFor="let entity of entities">
  <div>
    <img [src]="entity.imageUrl" (error)="onImageError(entity)" width="70" alt="IMAGE"/>

How can I rewrite entity.imageUrl inside onImageError() ?

I have tried following:

  onImageError(entity: IEntity) {
    entity.imageUrl = 'some-image.svg'
  }

But it says

36:3 error expected call-signature: 'onImageError' to have a typedef (tslint:typedef) @typescript-eslint/tslint/config

tillias
  • 1,035
  • 2
  • 12
  • 30

2 Answers2

2

The property bindings are TS expressions. You could you in theory simply say

<img [src]="entity?.imageUrl || alternateUrl" width="70" alt="IMAGE"/>
ruth
  • 29,535
  • 4
  • 30
  • 57
  • I have tried it and it doesn't work unfortunately. The thing is that entity.imageUrl is required field, but there might be some invalid url or url pointing to non-existing image – tillias Oct 03 '20 at 09:55
1

Probably your error is due to some typescript settings.

I would suggest you to either change the value inline like

(error)="entity.imageUrl = 'some-image.svg'" 

or define the return type on the function as void

onImageError(entity: IEntity):void {
    entity.imageUrl = 'some-image.svg'
}

Hope this helps!

navdbaloch
  • 191
  • 12
  • It is now deprecated, what I already stated in original question (see https://stackoverflow.com/questions/57979955/what-should-i-use-instead-of-the-deprecated-onerror-attribute). No onerror please – tillias Oct 03 '20 at 10:32
  • Thanks for pointing out that, I have updated my code to just what you did and it worked. probably your error is due to some typescript settings. I would suggest you to either change the value inline like '(error)="entity.imageUrl = 'some-image.svg'" or define return type on the function as void 'onImageError():void'. hope this helps – navdbaloch Oct 04 '20 at 06:40
  • That is exactly the point, for ts 2.7 (or whatever is in newest angular) onerror is deprecated and all previous advices on stack overflow are related to earlier versions. I will check your suggestion from comment and report results here shortly. – tillias Oct 04 '20 at 07:00