【问题标题】:How to change the images dynamically inside for loop in angular6?如何在angular6的for循环中动态更改图像?
【发布时间】:2019-04-13 20:38:08
【问题描述】:

我的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 显示的每个按钮动态更改图像。谁能给我一些建议来实现它?

【问题讨论】:

    标签: html css angular angular5 angular6


    【解决方案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 属性,该属性将具有imagepath

    如果要更改整个图像的路径,则可以使用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;
    }
    

    【讨论】:

    • 感谢您的回复。我可以看到按钮 onload 的图像。我想要的是单击按钮,我需要为每个按钮用另一个图像替换图像。你能告诉我怎么做吗?
    • &lt;img [src]= horizontal.items.items[selectedIndex].icon class="icon"/&gt;更新了答案
    • 非常感谢。图像在变化,但对于每个按钮,我都会得到相同的图像。 (例如,如果我单击第一个按钮,按钮的图像需要更改为 aaa,如果我单击第二个按钮,则按钮的图像需要更改为 bbb)
    • 我在编辑部分更新了答案。请检查它是否适合您。
    • 它仍然不适合我。如果有的话,你能给我任何其他的解决方案吗?请..
    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2020-10-13
    • 2020-06-17
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多