javascript - 单击时在 html 中的三个图标之间切换
问题描述
我有一个按钮,每次点击都会改变图标。该按钮有下一个箭头、后退箭头、停止图标。处理按钮的最佳方式是什么,所以每次点击图标都会改变。
HTML:
<button (click)="toggleBtn()">
<span *ngIf="selectedIcon='left'" class="icon-left"></span>
<span *ngIf="selectedIcon='right'" class="icon-right"></span>
<span *ngIf="selectedIcon='stop'" class="icon-stop"></span>
</button>
零件:
public ngOnInit() {
this.selectedIcon="Both"; //default selection to display to user.
}
public toggleBtn(){
// how should i handle the toggle? User a for loop in my component or switch?
// what would be the ideal way of achieving this.
}
解决方案
//in your .ts declare a variable index
index:number=0;
//in your .html
<button (click)="index=(index+1)%3">
<span [ngClass]="{'icon-left':index==0,'icon-right':index==1,'icon-stop':index==2}">
更新 如果您有多个项目,则需要多个变量。通常你可以有一个对象数组 [{item:'uno',index:0}{item:'dos',index:0}..]。在 *ngFor="let item of myArray"> 中,将“index”替换为“item.index”
//In your .ts
myArray:any[]=[{desc:'uno',index:0},{desc:'dos',index:0}..];
//If you have an array of object but you don't have the property "index"
//You always can "map" the array to add the property
//e.g
anotherArray=["uno","dos"];
//transform the array
this.anotherArray=thia.anotherArray.map(x=>return{
desc:x,
index:0
})
<button *ngFor="let item of my array" (click)="item.index=(item.index+1)%3">
<span [ngClass]="{
'icon-left':item.index==0,
'icon-right':item.index==1,
'icon-stop':item.index==2}">{{item.desc}}
</button>
更新两个 我们可以有不同的按钮,但不能在 *ngFor 中为此,使用索引数组
//in ts
index:number[]=[0,0]
//in .html
<!--for the first button we use index[0]-->
<button (click)="index[0]=(index[0]+1)%3">
<span [ngClass]="{
'icon-left':index[0]==0,
'icon-right':index[0]==1,
'icon-stop':index[0]==2}">
</button>
<hr/>
<!--for the second button we use index[1]-->
<button (click)="index[1]=(index[1]+1)%3">
<span [ngClass]="{
'icon-left':index[1]==0,
'icon-right':index[1]==1,
'icon-stop':index[1]==2}">
</button>
<hr/>
推荐阅读
- javascript - Wix:移动视图中的隐藏灯箱仍然显示一些阴影
- r - 在 R 中使用 FTC api 提取 50 多个结果
- javascript - 当您有多个来自 PHP 循环的表单时,如何通过 AJAX 提交单个表单
- mongodb - MongoDB计数按数组元素分组的数组中的匹配字符串
- excel - 检索小于给定日期的第一个日期不工作 Excel
- visual-studio-code - VS Code:用户和工作区的设置有什么区别
- mongodb - Mongo服务器错误“无法建立连接,因为目标机器主动拒绝了它。”
- python-xarray - getting KeyError '.zmetadata' when opening remote zarr store
- r - How to use mapply to perform function on columns of two lists in R?
- python - 在 Python pandas 数据框中添加计数器作为附加列