0

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.

Harsha Mullangi
  • 474
  • 1
  • 6
  • 27

3 Answers3

1

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

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
0

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'
}
chana
  • 183
  • 2
  • 19
0

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>
souravmsh
  • 638
  • 6
  • 11