1

I have this call inside my html file:

profile.html

<div mat-card-avatar *ngIf="imgResult" [ngStyle]="{ 'background-image': 'url(' + imgResult + ')' }" class="avatar">
  <mat-icon *ngIf="!imgResult">person</mat-icon>
</div>

My component is like this:

profile.component.ts

import { DomSanitizer } from '@angular/platform-browser';

...

  picture: File;
  imgResult: any;

...

constructor(
    private sanitizer: DomSanitizer
  ) { }

...

  onChange(event) {
    this.picture= event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(this.picture);
    reader.onload = (ev: any) => {
      this.imgResult = ev.target.result;
      return this.sanitizer.bypassSecurityTrustUrl(this.imgResult);
    };
  }

The picture load is working as expected but, I can't stop the sanitizing unsafe URL value warning.

How can I do that?

Diego de Lima
  • 471
  • 2
  • 7
  • 15

1 Answers1

1

You are using the sanitizer correctly but not using the result value. Try this instead:

reader.onload = (ev: any) => {
  const trustedUrl = this.sanitizer.bypassSecurityTrustStyle(`url(${ev.target.result})`);
  this.imgResult = trustedUrl;
};

And use this in html file instead:

[style.background-image]="imgResult"

This question is already answered at this topic: WARNING: sanitizing unsafe style value url

Diego de Lima
  • 471
  • 2
  • 7
  • 15
David G.
  • 1,255
  • 9
  • 16
  • Thanks @David but It didn't work. If I use this code that you suggested me, the picture isn't loaded and the warning persists. – Diego de Lima Oct 21 '19 at 20:36
  • Can you try using the method bypassSecurityTrustResourceUrl instead? – David G. Oct 21 '19 at 21:17
  • I tried. But the issues persist: not loading the picture and warning message (still the same) – Diego de Lima Oct 21 '19 at 21:25
  • I have found this. If you check the most upvoted answer it is quite similar to yours. Let's see if that does it, it would actually make sense for it to be a style resource: https://stackoverflow.com/questions/38593515/warning-sanitizing-unsafe-style-value-url – David G. Oct 21 '19 at 21:40
  • thank you so much! I've spent a lot of time during today on searching a topic which could help me and didn't find this one, even during posting this question. Now it's working. I'll keep this question only as an alternative for new searches and post the link and details in your answer. – Diego de Lima Oct 21 '19 at 21:54