Search code examples
cssangulartypescriptbackground-imagehtml-sanitizing

Sanitizing unsafe style value for background-image using ngStyle with conditional expression


I am trying to display background image of a div dynamically using ngStyle. I also have fallback image if the default value is null.

    <div class="card-img-top" 
    [ngStyle]="{'background-image': process.thumbnail != null ? 'url(data:image/png;base64,' + 
    process.thumbnail +')' : 'url(./assets/default-thumbnail.png)' | safeHtml}"
    >

although this works fine, I get warnings in console as below for all the thumbnails

core.js:6462 WARNING: sanitizing unsafe URL value data:image/pngbase64,iVBORw0KGgoAAAANSUhEUgAAAQIAAABxCAYAAAA+..

Sanitizing the url with safePipe still gives me warning. I'm not sure if I'm implementing it in right way

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

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(value) {
    return this.sanitizer.bypassSecurityTrustStyle(value);
  }}

Solution

  • Replacing [ngStyle] with [style.background-image] worked for me. Sanitizing the style is not required.

    <div class="card-img-top" 
    [style.background-image]="process.thumbnail != null ? 'url(data:image/png;base64,' + 
    process.thumbnail +')' : 'url(./assets/default-thumbnail.png)'" >