Syertim
Syertim

Reputation: 157

Using a dynamic name for image source in Angular

I have some decks of cards. I want to display a specific image for each deck, I have an assets folder with all my images.

<div class="decks">

  <div *ngFor="let deck of decks" class="deck">

    <img
    src="../../assets/img/MAGE.png" 

MAGE is just an exemple of a deckClass, that name should match deck.deckClass

  class="img-responsive"
  style="height: 200px;">

  <h4> {{deck.deckName}} : {{deck.deckClass}} </h4>
  <p *ngFor="let card of deck.deckCards" >
    {{ card.name }} : {{ card.manaCost }}
  </p>

</div>
</div>

How can I concatenate in a src attribute the deck.deckClass name in a dynamic way?

Upvotes: 0

Views: 457

Answers (1)

Zano
Zano

Reputation: 86

Consider using the Expression Context

You can wrap the sry attribute with square brackets, this way Angular will know to evaluate the value:

[src]="'../../assets/img/' + deck.deckClass '.png'"

See a demo here: https://stackblitz.com/edit/angular-ua9cfc
I don't have images in there, so they will be shown as broken img's in the demo ...

p.s.: if those images are in your src/assets/ folder, then this should suffice:

[src]="'assets/img/' + deck.deckClass '.png'"

Upvotes: 2

Related Questions