Alexander Belov2017-02-02 23:44:02
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) { }

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

  		(data) => this.cartItems = data



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

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

Something like this. Code not tested

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

  		(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