简体   繁体   中英

How can I change .css class property - background: url('') for each item javascript / typescript

This is how I display products from database:

<div *ngFor="let product of products;">
  <div id="article1" class="article">
    <p class="product-price">{{product.mpc | number}}</p>
    <p class="product-title">{{product.title}}</p>
  </div>
</div>

As you can see there is .css class "article" on with id="article1"..

And here is the .css article class:

.article {
  background-color: black;
  cursor: pointer;
  background: url('../../src/assets/images/funny-photo.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center, center;
}

As it is possible to see background: url of this class .article is hardcoded:

background: url('../../src/assets/images/funny-photo.jpg');

How can I for each item set different background: url with corresponding url from database?

Thanks guys Cheers

Use [style.background] and set in url the url from current product

<div *ngFor="let product of products;">
  <div id="article1" class="article" [style.background]="'url('+product.image+')'">
    <p class="product-price">{{product.mpc | number}}</p>
    <p class="product-title">{{product.title}}</p>
  </div>
</div>

if its angular then try

<div [ngStyle]="{'background-image': 'url(' + photoURL + ')'}"></div>

Inside your ngFor loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM