A
A
Alexander Belov2017-02-02 23:44:02
Angular
Alexander Belov, 2017-02-02 23:44:02

Angular2 / How to setup DomSanitizer?

The task is to write background-image inline in Angular2.
I'm trying to use DomSanitizer. In the class I prescribe the invariable part of the URL for all loaded images + under the this.image line I add unique "tails" of the URL. In my understanding, I "cleaned up" the URL and now it should not cause security errors.

export class AppComponent {
  cartItems: any;
  image: any;

  constructor(public cartService: CartService, private sanitizer: DomSanitizer) { }

  ngOnInit(){
  	let sanitizedUrl = this.sanitizer.bypassSecurityTrustUrl('https://s27.postimg.org/' + this.image);

  	this.cartService.getCartItems().subscribe(
  		(data) => this.cartItems = data
  	);

  }

}

In view I use inline styles:
<span class="col cart__item--imageBox" 
[style.background-image.url]="('sanitizedUrl' + cartItem.image)">
</span>

In the console I get this:
WARNING: sanitizing unsafe style value sanitizedUrl<<тут уникальные URL "хвосты" картинок>> (see http://g.co/ng/security#xss).

That is, for some reason it still does not accept the "stripped" URL.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2017-02-03
@AMar4enko

Something like this. Code not tested

ngOnInit(){
        let addSanitizedUrl = (item) => {
          item.sanitizedImageUrl = this.sanitizer.bypassSecurityTrustUrl('https://s27.postimg.org/' + this.image + item.image)
          return item;
        };

  	this.cartService.getCartItems().subscribe(
  		(data) => this.cartItems = data.map(addSanitizedUrl)
  	);

  }

<span class="col cart__item--imageBox" [style.background-image.url]=cartItem.sanitizedImageUrl"></span>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question