0

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>
MadMac
  • 4,048
  • 6
  • 32
  • 69
  • 3
    Possible duplicate of [WARNING: sanitizing unsafe style value url](https://stackoverflow.com/questions/38593515/warning-sanitizing-unsafe-style-value-url) – Elias Soares Oct 01 '19 at 21:54
  • So... that duplicate _almost certainly_ was offered to you when you were writing this question. Just curious why you didn't mention it in your question, or if you reviewed it? – random_user_name Oct 01 '19 at 21:55
  • I did see that and I tried the suggested solution but could not get it to work. In future I will mention what I have already tried. – MadMac Oct 01 '19 at 23:36

2 Answers2

2

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);
  }
MadMac
  • 4,048
  • 6
  • 32
  • 69
1

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>
Amir Christian
  • 597
  • 6
  • 20
  • Thanks, that's got it. I thought I had tried that but I guess not. I have another solution that works (I will add below) but yours is better so I will accept this one. – MadMac Oct 01 '19 at 22:16