PAR
PAR

Reputation: 441

Dynamically adding image

I am building an Angular app. I need to add different images to each button.

HTML:

<div *ngFor="let Items of myItems">
    <button class="close-image"><img src="../../assets/img/flower.png">
        <span>         
        </span> 
    </button>
</div>

From above code I am creating buttons depend on response (example: four buttons), and all buttons contain same image. How should I add different images to each of these ngFor buttons?

Upvotes: 0

Views: 145

Answers (2)

Tomasz Kula
Tomasz Kula

Reputation: 16857

html

<img *ngFor="let image of images" [src]="image">

component

images = [
  'path/to/image/1',
  'path/to/image/2',
  'path/to/image/3',
];

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191819

You can use the input binding [src] to specify the source from properties. Let's assume that Items has an imgSrc property:

<div *ngFor="let item of myItems">
  <button class="close-image"><img [src]="item.imgSrc">
    <span>{{item.text}}</span> 
  </button>
</div>

You can also concatenate strings in this binding if you need to specify the path

[src]="'../../assets/img/' + item.imgSrc"

This assumes that myItems looks something like this (whether it comes from a server or is hard coded):

myItems = [
  { imgSrc: 'flower.png', text: 'Flower' },
  { imgSrc: 'flower2.png', text: 'Flower2' },
];

Upvotes: 2

Related Questions