1

I am trying to use background-image inline for my *ngFor list items. Im my Component Class I declare a variable which stores a common part of my images URL (say, it's http://storage.com/) and also unique parts of URLs of the images as this.image (say, they are qwerty/01.jpg, uiop/02.jpg, asdfg/03.jpg, etc)

All together it looks like

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 the view I have where cartItem is an item over generated *ngFor list:

<span class="col cart__item--imageBox" 
[style.background-image.url]="('sanitizedUrl' + cartItem.image)">
</span>

Console shows 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 supposed the URL to be "sanitized".

What should be done to be able to use background-image styles inline as in my example above?

UPD! I rewrote my NgOnInit function into that:

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) 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)
  );

}

The Warnings disappeared, but it seems like the app doesn't find any of my images passed in the service. Just can't find them via DevTools Inspector.

yugr
  • 19,769
  • 3
  • 51
  • 96
Alexandr Belov
  • 1,804
  • 9
  • 30
  • 43

1 Answers1

0

Only a part of your URL is sanitized. To fully sanitize it,

Add a method to your component for sanitization as

sanitize(url:string){
    return this.sanitizer.bypassSecurityTrustUrl(url);
  }

and you HTML will be calling the above method before URL is passed as below

<span class="col cart__item--imageBox" 
[style.background-image.url]="sanitize('sanitizedUrl' + cartItem.image)">
</span>

Also it is just a warning and can be ignored.

Aravind
  • 40,391
  • 16
  • 91
  • 110