Search code examples
htmlangulartypescriptbase64angular6

How can I display image encoded in base64 format in Angular 6?


I struggle with a problem associated with Angular 6 and displaying image encoded in base64 format. Any ideas why code shown below doesn't display image?

html:

<tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
<img src="{{this.hello}}" />

ts:

this.hello = "data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."

While code shown below works properly and displays picture?

html:

<tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
<!--<img src="data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."/>

this.hello is assigned in the constructor just for test purpose. I create it in this way this.hello = 'data:image/png;base64, ' + this.UploaderService.imageRecognitionRowsData[0].toString() My main goal is to display imageRecognitionRowsData in this loop <tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">. So for first iteration I would display image imageRecognitionRowsData[0] then during next iteration image imageRecognitionRowsData[1] etc. The length of this.UploaderService.tableImageRecognition.dataRows is always the same as this.UploaderService.imageRecognitionRowsData When I add <p>{{this.hello}}</p> I get the same string in html. I have no idea what is wrong. I tried also with this.hello2 = this.sanitizer.bypassSecurityTrustResourceUrl(this.hello);, this.hello2 = this.sanitizer.bypassSecurityTrustUrl(this.hello);, <img [src]="this.hello" /> etc. but nothing works. Any ideas how to solve this?


Solution

  • You don't use "this" to refer the variables defined in the component "ts" file. Remove "this" may solve your problem.

    Please Review this stackbliz Fiddle. Look inside the app component to see the implementation.

    StackBlitz