2

I have a couple of cards that pull data from an API and then loop over the data to display the cards in the front end. each card has an image associated to it that I'd like to set as a background image for each specific card.

<div *ngFor ='let package of packages; let i = index' [attr.data-index]="i">
     <div class="card"> 

        <div class="card-header" style="background-image:url("{{packages[i].destinations.image}}")">{{packages[i].destinations.destname}}</div>
        <div class="price">{{packages[i].destinations.hotelrating}}</div> 

     </div>
 </div>

this is obviously not working. i search on the forum but cannot find any method that shows how to handle setting background images for cards getting the data from an API

2 Answers 2

4

What you are missing is adding a dynamic CSS style attribute. Angular supports adding dynamic CSS style attributes to any element while at runtime. For that, you can use the one of the below arrangements:

<div [ngStyle]="{background: 'url('+ packages[i].destinations.image + ')'}"></div>

Or

<div [style.background]="'url('+ packages[i].destinations.image + ')'"></div>

Or else if you want add dynamic css class depending upon conditions you can use below :

<div [ngClass]="{ 'class1': condition, 'class2': !condition }"

Sign up to request clarification or add additional context in comments.

3 Comments

not sure i understand. I am using scss in the project. could you elaborate please?
you have an error in your code above. you need to add the + sign afer url as well.
@GavinWood In angular you can you can use dynamic css classes. lets say you want to add a css class dynamically depending on certain condition in angular which depends on API data? You can accomplish it using [ngStyle] or ngClass while passing an condition like this <div [ngClass]="{ 'class1': condition, 'class2': !condition }">
2

You can use [ngStyle] to set image dynamically.

Try like this:

[ngStyle]="{'background-image': 'url(' + packages[i].destinations.image + ')'}"

Working Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.