Reputation: 147
img tag throwing an error 404 when img is not available instead of throwing an error I want one avtar image with the first char of user name should come. suppose user name Ravi than R should come instead of error
I have tried with the boolean flag but it doesn't work for me for getting first char i have tried in alt attribute list.name.charAt(0) but still, img error is coming
<ion-item lines="none">
<ion-thumbnail slot="start" rounded >
<ion-img [src]="'assets/icon/' +list?.type+ '.png'" >
</ion-img>
</ion-thumbnail>
<ion-text slot="end"></ion-text>
<ion-button (click)="doAdd(list.type ,'')" slot="end">
Add link
</ion-button>
</ion-item>
output should when img is not available then user first char of name should come instead of error
Upvotes: 0
Views: 1488
Reputation: 6488
Images have the onerror
property, for ionic it is ionError
(see docs), you can use to execute code.
<img [src]="'assets/icons/'+list?.type+'.png'" (ionError)="handleError(i)">
There you can set an alternative src
attribute for your image instead.
export class MyPage {
list: YourListType[];
handleError(index: number) {
this.list[index].type = 'alternative-image-name';
// note that in your template you concat that with the `assets/icon` path and the .png ending
}
}
Upvotes: 5
Reputation: 736
Can you try like this.i hope your error will solve
imageUrl(list){
if(list.type){
return "assets/icon/" + list?.type + ".png"
} else {
return "assets/icon/avatar.png"
}
}
<ion-item lines="none">
<ion-thumbnail slot="start" rounded >
<ion-img [src]="imageUrl(list)" >
</ion-img>
</ion-thumbnail>
<ion-text slot="end"></ion-text>
<ion-button (click)="doAdd(list.type ,'')" slot="end">
Add link
</ion-button>
</ion-item>
Upvotes: 0