MadMac
MadMac

Reputation: 4841

Angular WARNING: sanitizing unsafe style value

UPDATE: I recommend people look in the link above first as there are some good solutions.

However I could not get any of them to work for my particular case as my issue was not related to a url but width and height.

Question:

I am getting the following warning in the console with the following code:

WARNING: sanitizing unsafe style value calc(300px * 0.7509025270758123) (see http://g.co/ng/security#xss).

The code works fine but it is run for every image on my page and fills up the console.

Any ideas how to remove the warning?

<div 
   *ngIf="swipeFile.imageUrl" 
   class="linear-background" 
   [ngStyle]="{'width': '300px', 'height': 'calc(300px * ' + (swipeFile.imageHeight / swipeFile.imageWidth) + ')'}" >
   <img mat-card-image [src]="swipeFile?.imageUrl" alt="image">
</div>

Upvotes: 0

Views: 1222

Answers (2)

MadMac
MadMac

Reputation: 4841

This also works but the answer from @Amir is better.

<div *ngIf="swipeFile.imageUrl" class="linear-background" [style]="getSanitizedStyle('width: 300px; height: ' + (300 * (swipeFile.imageHeight / swipeFile.imageWidth)).toFixed(0) + 'px')" >

.ts

constructor(private sanitizer: DomSanitizer) { }

 public getSanitizedStyle(style: string) {
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }

Upvotes: 2

Amir Christian
Amir Christian

Reputation: 595

Please try this

    <div 
       *ngIf="swipeFile.imageUrl" 
       class="linear-background" 
       [ngStyle]="{'width': '300px', 'height': (swipeFile.imageHeight / swipeFile.imageWidth) * 300 + 'px'}" >
       <img mat-card-image [src]="swipeFile?.imageUrl" alt="image">
    </div>

Upvotes: 1

Related Questions