Adding external background image dynamically Angular 2 sanitizer

3k views Asked by At

I'm trying to add a background image within an ngFor loop

After getting warnings

WARNING: sanitizing unsafe style value url…

I looked into using the DomSanitizer, but I am still having trouble getting it to work, either I see no style attached or

SafeValue must use [property]=binding

this is how I'm declaring the url variable

res.map(items=>{

let url = "https://img.youtube.com/vi/"+ items.vidUrl + "/0.jpg";

items.vidUrl =  this.sanitizer.bypassSecurityTrustStyle("'background-image': 'url("+url+")'")
         });

this.blogs = res;

When logged, it shows that items.vidUrl is updated correctly

And the HTML

<div class="col-4 card" *ngFor="let blog of blogs">
<div class="bg-cover"  [ngStyle]="blog?.vidUrl" ></div>
</div>
1

There are 1 answers

2
RasMason On

Got it working by changing

items.vidUrl =  this.sanitizer.bypassSecurityTrustStyle("'background-image': 'url("+url+")'")
         });

to

items.vidUrl =  this.sanitizer.bypassSecurityTrustStyle("url("+url+")")
         });

and in the HTML

<div class="bg-cover"  [style.background-image]="blog?.vidUrl" ></div>