this is my component html.
<div *ngFor="let getData of activePage">
<img [src]="svgsData(getData)" />
</div>
How do I store that result svgsData(getData)
into class member and use that in template? here how I am getting svgsData
in typescript.
preview:any = [];
activePage:any = []
svgsData(image) {
let base64string = btoa(image);
return this._sanitizer.bypassSecurityTrustResourceUrl(
`data:image/svg xml;base64,${base64string}`
);
}
previewSvg() {
this.systemComponent.fetchData().then(data =>{
this.preview = data;
this.activePage = this.preview.slice(0,this.pageSize);
}).catch(error =>{
console.log(error)
});
I have tried this but that doesn't display the data:
previewSvg() {
this.systemComponent.fetchData().then(data =>{
this.preview = data;
this.svgsData(this.preview);
this.activePage = this.preview.slice(0,this.pageSize);
}).catch(error =>{
console.log(error)
});
<div *ngFor="let getData of activePage">
<img [src]="getData" />
</div>
CodePudding user response:
It's highly ill advised to use method callbacks in template e.g svgsData(getData)
. Each time page is rendered, this method is called. Possibly hundreds of times.
Instead use pure pipes to run pipe each time prop is changed. A | safe
pipe to clean and transform base64 string to content.
<div *ngFor="let getData of activePage">
<img [src]="getData | safe" />
</div>
import { Pipe, PipeTransform, Sanitizer } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safe',
})
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {}
transform(image: string) {
return this._sanitizer.bypassSecurityTrustResourceUrl(image);
}
}
Example: https://stackblitz.com/edit/creating-a-custom-pipe-in-angular-aho9ax?file=src/app/safe.pipe.ts