You have to wrap the entire url
statement in the bypassSecurityTrustStyle
:
<div class="header" *ngIf="image" [style.background-image]="image"></div>
And have
this.image = this.sanitization.bypassSecurityTrustStyle(`url(${element.image})`);
Otherwise it is not seen as a valid style property
Use this <div [ngStyle]="{'background-image':'url('+imageUrl+')'}"></div>
this solved the problem for me.
If background image with linear-gradient (*ngFor
)
View:
<div [style.background-image]="getBackground(trendingEntity.img)" class="trending-content">
</div>
Class:
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
constructor(private _sanitizer: DomSanitizer) {}
getBackground(image) {
return this._sanitizer.bypassSecurityTrustStyle(`linear-gradient(rgba(29, 29, 29, 0), rgba(16, 16, 23, 0.5)), url(${image})`);
}
I got the same issue while adding dynamic url in Image tag in Angular 7. I searched a lot and found this solution.
First, write below code in the component file.
constructor(private sanitizer: DomSanitizer) {}
public getSantizeUrl(url : string) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
Now in your html image tag, you can write like this.
<img class="image-holder" [src]=getSantizeUrl(item.imageUrl) />
You can write as per your requirement instead of item.imageUrl
I got a reference from this site.dynamic urls. Hope this solution will help you :)
Check this handy pipe for Angular2: Usage:
in the SafePipe
code, substitute DomSanitizationService
with DomSanitizer
provide the SafePipe
if your NgModule
<div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With