angular - 一次只选择一个复选框,并在一个特定复选框被选中或两个复选框都未选中时执行特定任务
问题描述
我有两个复选框,目标是一次只允许选择一个复选框 根据对特定复选框的选择或者如果两个复选框都未选中,则需要执行更多不同的任务。当检查一个复选框或两者都没有选中时,我在执行任务时已经实现了这一问题并面临问题。
<div *ngFor="let chk of checkboxes">
<input type="checkbox" [checked]="chk.checked"
(click)="uncheckOther(chk)"> {{chk.value}}
</div>
TS 代码:
checkboxes = [{ checked: false, value: 'Request' }, { checked: false,
value: 'Reservation' }];
uncheckOther(chk) {
//uncheck all
this.checkboxes.forEach(x => {
if(x.checked == true)
x.checked = false;
})
//check the selected
if(chk.checked == true) {
chk.checked = false;
} else {
chk.checked = true;
}
//Execute task if any one of the checkboxes are selected
if(chk.value === "Request" && chk.checked == true){
console.log("call request data")
} else if(chk.value === "Reservation" && chk.checked == true){
console.log("call Reservation data");
}
//Execute task if none of them is checked
this.checkboxes.forEach(x => {
if(x.checked === false)
console.log("call both combined data")
})
}
一次只能选择一个复选框,并且需要执行一些任务,具体取决于选定的复选框或两个复选框都未选中,这也是默认情况(或用户可能未选中)
解决方案
需要一些改动:
HTML 代码:
<div *ngFor="let chk of checkboxes">
<input type="checkbox" [(ngModel)]="chk.checked" (ngModelChange)="uncheckOther(chk,$event)">
{{chk.value}}
</div>
TS 代码:
uncheckOther(chk, event) {
if (event) {
//uncheck all
this.checkboxes.forEach(x => {
if (x.checked == true)
x.checked = false;
})
//check the selected
if (chk.checked == true) {
chk.checked = false;
} else {
chk.checked = true;
}
if (chk.value == "Request") {
console.log('Call Request API')
}
else if (chk.value == "Reservation") {
console.log('Call Reservation API')
}
}
else {
console.log('Call Both API')
}
}
推荐阅读
- android - 如何在 Android 上有效地测试多线程、多进程、多设备代码?
- mysql - mysql unix_timestamp 重复日期时间
- css - 使用来自另一个元素的选择器定位一个元素
- java - 如何在一个片段中显示我的微调器
- c - 用于套接字 SSL 的 Windows API
- java - 如何提高与空间搜索相关的 Solr 查询的性能?
- javascript - 如何将视频数据发送到 Kinesis Video Stream?
- c++ - 在指向各种 Person 实例的 unique_ptrs 向量中访问名为 Truck 的派生类的成员函数的语法是什么?
- csv - 源文件连接(平面文件) - 不读取列元数据
- wix - 在 WIX 中设置对话框序列和自定义