0

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?

3
  • save image paths in array in your .ts file. then use ngfor Commented Mar 26, 2018 at 13:16
  • have you created model for myItems, if so. You can add image field to that modal. while getting myItems value, you can assign image value to that key. So in markup you can get image Commented Mar 26, 2018 at 13:21
  • Same like @Explosion Pills' answer Commented Mar 26, 2018 at 13:28

2 Answers 2

2

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' },
];
Sign up to request clarification or add additional context in comments.

Comments

0

html

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

component

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.