Harsha Mullangi
Harsha Mullangi

Reputation: 564

show the image based on a condition

I want the image tag to show the image depending on a condition.

I tried the below code but it is not showing me the image

<img src="{{row.image}}!=null?'data:image/jpeg;base64,{{row.image}}':'./assets/img/quill1.png'">

Can someone tell what is that i am doing wrong.

Upvotes: 0

Views: 2979

Answers (3)

souravmsh
souravmsh

Reputation: 638

You can try this.

Sometimes browser does not support the untrusted URL that is the reason you should use bypassSecurityTrustUrl due to security issues. You can see the documentation https://angular.io/api/platform-browser/DomSanitizer

component.ts

import { DomSanitizer } from '@angular/platform-browser'; 

constructor(private xss: DomSanitizer) {}

safeURL(url: string): any {
    return this.xss.bypassSecurityTrustUrl(url);
}

component.html

<img [src]="row.image?safeURL('data:image/jpeg;base64,'+row.image):'/assets/img/quill1.png'"  alt="Avatar">   

Or

<img [src]="safeURL('data:image/jpeg;base64,'+row.image)" onError="this.src='/assets/img/quill1.png'" alt="Avatar">   

Or

<img *ngIf="row.image; else noAvatar;" [src]="safeURL('data:image/jpeg;base64,'+row.image)" alt="Avatar"/> 
<ng-template #noAvatar>
  <img [src]="'./assets/img/quill1.png'" alt="No Avatar">
</ng-template>

Upvotes: 0

chana
chana

Reputation: 241

So you can split this into two elements:

<img *ngIf="row.image" [src]="'data:image/jpeg;base64,' + row.image" />
<img *ngIf="!row.image" src="./assets/img/quill1.png" />

or you can bind the result to a get function in your .ts file:

html:

<img [src]="getImage"/>

ts:

get getImage() {
       return  this.row.image!=null?'data:image/jpeg;base64'+this.row.image:'./assets/img/quill1.png'
}

Upvotes: 0

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

Use *ngIf to conditionally show elements

<img *ngIf="row.image" [attr.src]="'data:image/jpeg;base64,' + row.image" />
<img *ngIf="!row.image" src="./assets/img/quill1.png" />

Edit:

And you would ideally build the full base64 src string in your ts

Edit 2:

Example of conditional logic in attributes: https://stackblitz.com/edit/angular-cfbsid

This is not my recommended approach, just an example

Upvotes: 1

Related Questions