简体   繁体   中英

How to change the images dynamically inside for loop in angular6?

My html code:

          <div class="row">
        <div class="col-xs-6 col-sm-6 col-md-4 col-lg-12">
           <ng-container *ngFor="let horizontal of categories">
            <ng-container *ngFor="let horizontalval of horizontal.items;let i=index">
          <button [ngClass]="{'selected-color' : i==selectedIndex}" type="submit" class="btn1" [id]="horizontal.items[i].title" (click)="changeTrans(horizontal.items[i].title);changeColor(i)"> 
            <img [src]= horizontal.items[i].icon alt="image not found" class="icon"/>
            {{ horizontal.items[i].title }}
          </button>
        </ng-container>
      </ng-container></div>
      </div>

So my component.ts file,

 changeColor(i){
  console.log(i);
this.selectedIndex = i;
}

my css:

.selected-color{
 background-color: orange;
 color:white;
// background-image: url('./../../../../../assets/Trans_1.png');
}

So here I am able to change the color of the selected button, but I also need to change different images for different values. Here, how can I change my image dynamically for every button id?

Basically what I want to know is, how to change the image dynamically for every button which is going to be displayed via for. Can anybody suggest me something to achieve it?

Replace the below code

<ng-container *ngFor="let horizontalval of horizontal.items;let i=index">

by

<img [attr.src]= "horizontalval.icon" alt="image not found" class="icon"/>

Edit

Note : object horizontalval should have attribute icon which will have path of image .

If you want to change the path for entire image then you can use selectedIndex .

<img [src]= "horizontal.items[selectedIndex].icon" class="icon"/>

Edit

    <button [ngClass]="{'selected-color' : horizontal.items[i].selected}" 
      type="submit" class="btn1" [id]="horizontal.items[i].title"
 (click)="changeTrans(horizontal.items[i].title);
         changeColor(horizontal.items[i])">        
       <img [src]= horizontal.items[i].icon alt="image not found" class="icon"/>
                {{ horizontal.items[i].title }}
      </button>

ts

changeColor(item){
  this.item.selected = true;
}

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