thisdot / open-source

Repository for open source packages
MIT License
34 stars 11 forks source link

UseHttpImageSourcePipeModule does not work with [style.background-image] #127

Open Abvirk opened 2 years ago

Abvirk commented 2 years ago

What package and version are you using?

0.1.9

What browser are you using?

Chrome

What operating system are you using?

Windows

Actual Behavior

I have in using UseHttpImageSourcePipeModule to load authorized images. Its working fine with [src] attribute of image. When I try to use it with [style.background-image] attribute of div it always shows loading default image. Here is my code.

<div [style.background-image]="'url('+(img.path|useHttpImgSrc)+')'">

Expected Behavior

It should load image, as its loading image in [src] attribute.

Reproduction

<div [style.background-image]="'url('+(img.path|useHttpImgSrc)+')'">

Additional Information

No response

TapaiBalazs commented 2 years ago

@Abvirk Thank you very much for reporting this issue. I have investigated it a little and found the following:

The pipe's return type is string | SafeUrl. In case of images that are fetched with the httpClient inside the pipe, they are going to be blob urls like blob:http://localhost:4200/30e63884-d292-4516-9cdd-9e0b45023db5.

For these blob urls, the pipe calls this.domSanitizer.bypassSecurityTrustUrl(unsafeBlobUrl)) which will turn the return value into a SafeUrl.

I was able to reproduce your reported issue with the following code snippet:

<ng-container *ngIf="'https://thisdot-open-source.s3.us-east-1.amazonaws.com/public/success.png' | useHttpImgSrc as url">
    <div class="bg-image"
         [style.background-image]="'url(' + url + ')'"

    >
      should have background
    </div>

  </ng-container>

In this scenario the [style.background-image] gets a SafeUrl object when the image gets loaded successfully. I was able to work around the issue with the following code snippet:

<ng-container *ngIf="'https://thisdot-open-source.s3.us-east-1.amazonaws.com/public/success.png' | useHttpImgSrc as url">
    <div class="bg-image"
         [style.background-image]="'url(' + (url.changingThisBreaksApplicationSecurity ? url.changingThisBreaksApplicationSecurity : url) + ')'"

    >
      should have background
    </div>

  </ng-container>

I hope that the above workaround unblocks you for the time being, I assure you that we are going to look into how to fix this.

Possible solutions to the issue: