如何在angular6中的for循环内动态更改图像?

时间:2018-11-10 14:24:46

标签: html css angular angular5 angular6

我的html代码:

          <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>

所以我的component.ts文件

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

我的CSS:

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

因此,在这里我可以更改所选按钮的颜色,但是我还需要为不同的值更改不同的图像。在这里,如何为每个按钮ID动态更改图像?

基本上我想知道的是,如何动态地更改要通过for显示的每个按钮的图像。有人可以建议我实现目标吗?

1 个答案:

答案 0 :(得分:1)

替换下面的代码

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

作者

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

Edit

注意:对象horizontalval应该具有属性icon,该属性将具有path的{​​{1}}。

如果要更改整个图像的路径,则可以使用image

selectedIndex

编辑

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

ts

    <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>
相关问题