2

Trying to us a relative URL to set the background-image in a div. At the moment I'm trying to use a pipe:

<div [ngStyle]="{'background-image': 'url(' + banner + ')'}"></div>

A2 renders this in the markup:

<div _ngcontent-c2="" ng-reflect-ng-style="[object Object]" style="background-image: url(http://localhost:8080/assets/raster/banners/banner-background-02-800x300.png);">
</div>

I've tried using a pipe:

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

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

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

And this update in the markup:

  <div [ngStyle]="{'background-image': 'url(' + banner | safeHtml + ')'}">
  </div>

Which results in this error in the console:

"Template parse errors:
Parser Error: Missing expected } at column 49 in [{'background-image': 'url(' + banner | safeHtml + ')'}] in ng:///AppModule/AppBannerComponent.html@0:5 (\"<div [ERROR ->][ngStyle]=\"{'background-image': 'url(' + banner | safeHtml + ')'}\">
</div>\"): ng:///AppModule/AppBannerComponent.html@0:5"

I've tried wrapping the binding and pipe like so:

<div [ngStyle]="{'background-image': 'url(' + ( banner | safeHtml ) + ')'}">
</div>

But get this in the render:

<div _ngcontent-c2="" ng-reflect-ng-style="[object Object]"></div>

Trying to achieve this:

<div _ngcontent-c2="" *ng-reflect-ng-style="[object Object]"* style="background-image: url(/assets/raster/banners/banner-background-02-800x300.png);">
</div> <!-- or whatever ng-reflect-ng-style would be if the binding and piping are correct -->
Eric
  • 2,061
  • 8
  • 28
  • 37

1 Answers1

1

Alright, this a bit late answer but I just faced this today and solved by adding the HTML Entity Definitions &quot; to the css url parameter, like:

'url(&quot;'+ banner | safeHtml +'&quot;)'

So:

<div 
    [ngStyle]="{'background-image': 'url(&quot;'+ banner | safeHtml +'&quot;)'}">
  </div>

you also can use backgroundImage :

[ngStyle]="{backgroundImage: 'url(&quot;'+ banner | safeHtml +'&quot;)'}"

hope it helps...

caiovisk
  • 3,667
  • 1
  • 12
  • 18