Is it possible to utilize the onerror property of the img tag when src.bind is used?

Is it possible to utilize the onerror property of the img tag when src.bind is used?

For example, let’s say I want to use a default image if the src.bind one is not found/404:

<img src.bind="icon" onerror="this.onerror=null; this.src='/images/default-icon.jpg'"/>

Or, alternatives, remove the invalid image icon:

<img src.bind="icon" onerror="this.onerror=null; this.src=null;"/>

I can’t get it to work. I’m wondering if Aurelia is clearing out my onerror set value. Thoughts?

More can be found at this stackoverflow question on onerror and w3scools. Here is how Angular does it.

1 Like

I’d say to try using error.delegate or error.trigger

1 Like

Thanks. I’ll give that a shot.

1 Like

You can use onerror.bind=“getPlaceholder” on the html image, where getPlaceholder is a function on your component.

In my tests (Aurelia 1.3.1), the getPlaceholder method is ran within a closure where “this” refers to the image object, so from here simply set this.src = “[Url of placeholder image]”.

You can add dynamic fallback sources by adding a data attribute to the html image too, eg: add data-backupImage=“createBackupImage(viewModelObject)” as an attr on the image element, then refer to the attribute value in the getPlaceholder method by accessing: this.dataset.backupImage.

It’s 2021, but for someone that finds themselves here I hope this helps!

4 Likes