我的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显示的每个按钮动态地更改图像。有人可以建议我实现目标吗?

最佳答案

替换下面的代码

<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,该属性的pathimage

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

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


编辑

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

关于html - 如何在angular6的for循环中动态更改图像?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53239898/

10-12 12:35
查看更多