1
votes

I have a for loop showing images. The image is a background image of its container.

The images change on each iteration of the for loop.

The code:

<div class="row">
      <h4 id="rooms"><strong>Rooms</strong></h4>
      <button id="roomlinkbutton" class="linkbutton">+Room</button>
    </div>
    <div class="row" id="roomsrow"> <!--room row-->
      <div *ngFor="let room of venueprofileobject.rooms; let i=index" class="col-md-4"> <!--room item-->
        <div class="imagecontainer img-responsive imagefullheight"
             [style]=" background-image: url(room.image[0]);">
        </div>
        <h5 class="roomnameprivacy"><strong>{{room.name}} | {{room.privacy}}</strong></h5>
        <button (click)="deleteroom(i)" class="deleteroom btn-danger">Delete</button>
      </div> <!--room item-->

the code holding the images:

rooms:[
      {
        pk: 1,
        name: 'no',
        description: 'no',
        privacy: 'yeah',
        image: ['nifty porno image'],
        seatedcapacity: 2,
        standingcapacity: 2,
        amenities:['k'],
        setuptypes:['k'],
        filtercompliantroom: false
      },
    ]

but I am unsure how to bind the background-image url value with the image location.

Ive tried

style=" background-image: url({{room.image[0]}});"> which failed

[style]=" background-image: url(room.image[0]);"> which also failed

[style.background-image]="url(room.image[0])" failed as well

[ngStyle]="{'background-image': 'url('room.image[0]')'}" failed

suggestions?

currently looking at this page to see if I can find answers: https://www.concretepage.com/angular-2/angular-2-ngstyle-and-style-binding-example

1

1 Answers

2
votes

This is most likely due to Angular's built-in features to prevent cross-site scripting. See this link: https://angular.io/guide/security#xss

UPDATE

I was able to make it work with syntax like this:

<div class="row" [ngStyle]="{'background-image': 'url(' + imageUrl + ')'}">

This uses the ngStyle attribute which is "safe" instead of the style attribute.

This is what yours would need to look like:

<div class="row" [ngStyle]="{'background-image': 'url(' + room.image[0] + ')'}">

The syntax to the right of the colon (:) is basically building up a string, so you need to add "+" to concatenate the style text (such as 'url') and the value from the component property.