When using background-image inline for my *ngFor list items, I encountered an issue. In my Component Class, I defined a variable to store a common part of the images' URLs (e.g., ) along with unique parts of the image URLs as this.image (such as qwerty/01.jpg, uiop/02.jpg, asdfg/03.jpg, and so on).
The snippet in my AppComponent looks like this:
export class AppComponent {
cartItems: any;
image: any;
constructor(public cartService: CartService, private sanitizer: DomSanitizer) { }
ngOnInit(){
let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('http://storage.com/' + this.image);
this.cartService.getCartItems().subscribe(
(data) => this.cartItems = data
);
}
In my view, where cartItem is iterated over using *ngFor:
<span class="col cart__item--imageBox"
[style.background-image.url]="('sanitizedUrl' + cartItem.image)">
</span>
However, the console displayed warnings:
WARNING: sanitizing unsafe style value sanitizedUrl<<here go the images URLs endings - qwerty/01.jpg, uiop/02.jpg, asdfg/03.jpg, etc >> (see http://g.co/ng/security#xss).
I assumed the URL was "sanitized".
To address this issue, I updated my NgOnInit function as follows:
ngOnInit(){
let addSanitizedUrl = (cartItem) => {
cartItem.sanitizedImageUrl = this.sanitizer.bypassSecurityTrustStyle('https://s27.postimg.org/' + this.image + cartItem.image)
return cartItem;
};
this.cartService.getCartItems().subscribe(
(data) => this.cartItems = data.map(addSanitizedUrl)
});
After making these changes, the warnings disappeared. However, I am facing difficulties in finding the images passed in the service. They are not visible via DevTools Inspector.