我的网页包含
<ng-container *ngFor="let horizontal of categories">
<ng-container *ngFor="let horizontalval of horizontal.items;let i=index">
<button [ngClass]="{'selected-color' : i==selectedIndex }"
[ngStyle]="{'padding-top':horizontal.items[i].title==='Business'?'2.56%':(horizontal.items[i].title==='Plat' ? '2.56%':null)}"type="submit" class="btn1" [id]="horizontal.items[i].title"
(click)="changeImage(id);">
<img [src]= horizontal.items[i].icon alt="image not found" class="icon"/>
{{ horizontal.items[i].title }}
</button>
</ng-container>
我的ts文件:
changeImage(option){
if(option == "Trans"){
this.imgDefault = 'imgChange';
console.log("this.imgDefault :",this.imgDefault);
}
else if(option == "Col"){
this.imgDefault = 'imgChange1';
console.log("this.imgDefault :",this.imgDefault1);
}
else if(option == "Business"){
this.imgDefault = 'imgChange2';
console.log("this.imgDefault :",this.imgDefault2);
}
}
因此在我的CSS中,我保留了需要在单击按钮时更改的图像。
.imgChange{
background-image: url('../assets/Trans_2.png');
color:blue;
}
.imgChange1{
background-image: url('../assets/Trans_3.png');
color:blue;
}
.imgChange2{
background-image: url('../assets/Trans_4.png');
color:blue;
}
如何给img标签赋予条件,以便单击按钮以更改图像?
答案 0 :(得分:2)
您应在image
中添加div
,如下所示:-
imgDefault = 'imgChange'; <-- default;
changeImage(option){
if(option == "Trans"){
this.imgDefault = 'imgChange';
console.log("this.imgDefault :",this.imgDefault);
}
else if(option == "Col"){
this.imgDefault = 'imgChange1';
console.log("this.imgDefault :",this.imgDefault1);
}
else if(option == "Business Process Re-engineering"){
this.imgDefault = 'imgChange2';
console.log("this.imgDefault :",this.imgDefault2);
}
}
<ng-container *ngFor="let horizontal of categories">
<ng-container *ngFor="let horizontalval of horizontal.items;let i=index">
<button [ngClass]="{'selected-color' : i==selectedIndex }"
[ngStyle]="{'padding-top':horizontal.items[i].title==='Business'?'2.56%':(horizontal.items[i].title==='Plat' ? '2.56%':null)}"type="submit" class="btn1" [id]="horizontal.items[i].title"click)="changeImage(id);">
{{ horizontal.items[i].title }}
</button>
</ng-container>
</ng-container>
<div [ngClass]="imgDefault"></div>
链接:-https://stackblitz.com/edit/angular6-sqemmd?file=app/app.component.html
答案 1 :(得分:0)
您可以根据条件直接添加class
名称-您正在尝试从css
添加图像,将img
标签替换为div
,这将根据背景图像在class
上应用
请确保是否要循环显示图片,如果没有将div
移到*ngFor
之外
<div [class.imgChange]="imgDefault === 'imgChange'"
[class.imgChange1]="imgDefault === 'imgChange1'"
[class.imgChange2]="imgDefault === 'imgChange2'" ></div>
这将根据条件添加所有类,而div
将呈现img
-希望这能奏效!