4

I am trying to use dynamic image path as background image in one of my Angular6 project. I have tried using [style.background-image] & [style.background] even encodeURI to fix spaces in path also tried using *ngIF so that it renders after getting loaded.

Case 1:

imgPath is the absolute path, to which I am appending the path from JSON data.

HTML code

    <a routerLink="/article/{{news.id}}">        
      <img [style.background-image]="'url(' + imgPath + news.encodedImage.encocoded_primary_image + ')'">          
    </a>

Component

Checking images for spaces and other bracket using encodeURI() function

'encocoded_primary_image': encodeURI(res['primary_image']['file_path'])

Output

Image comparison of article

As seen in the picture "s/Absorica%20(2).png" is having brackets, which might be causing the bug but not sure though.

Other cases

I have tried with [style.background] , [ngStyle] , changing image tag to div tag.

But i am not able to understand why few of the images are rendering and few are not rendering, though path is getting generated correctly, which I have confirmed by opening them in new tab.

Any help will be highly appreciated

Gaurav Janoti
  • 96
  • 1
  • 10
  • Can you please provide a Demo in StackBlitz. I Am not sure if im understanding everything right. Which files are not working and which are ? Is there a pattern ? The brackets should not really bother angular – Joniras Dec 18 '18 at 10:28
  • @Joniras its solved now .. you can check below solution its working for me. – Gaurav Janoti Dec 28 '18 at 11:10

2 Answers2

5
  1. In background-image: url accepts the string. You have to add your image path to a string.

"'url(\'' + imgPath + news.encodedImage.encocoded_primary_image + '\')'"

<a routerLink="/article/{{news.id}}">
  <img [style.background-image]="'url(\'' + imgPath + news.encodedImage.encocoded_primary_image + '\')'">
</a>

https://developer.mozilla.org/en-US/docs/Web/CSS/background-image

https://www.w3schools.com/csSref/pr_background-image.asp

  1. Try using escape() method but this method has been deprecated. Careful using this.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape

Ashish Singh Rawat
  • 1,419
  • 16
  • 30
  • 1
    right .. escape() is deprecated and encodeURI() might ditch you in few of the special characters so better to make image path as string. – Gaurav Janoti Dec 28 '18 at 11:18
0

don't use any ElementRef, DomSanitizer

in component :

img = '';
data(){       //image url -> if it comes from anywhere & any time
   this.img = 'http://img.....'
}

in template: use in any supported tag

<div style="background-repeat: no-repeat; background-size: cover;"
 [style.background-image]='"url(\"" + banner + "\")"'></div>

//or

<div style="background-repeat: no-repeat; background-size: cover;"
 [style.background-image]="'url(\'' + banner + '\')'"></div>
rajkanani
  • 173
  • 3
  • 5