gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:46:34 25 4
gpt4 key购买 nike

我的 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"/>

编辑

注意:对象 horizo​​ntalval 应具有属性 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;
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com