我有两个复选框,目标是一次只允许选中一个复选框 根据特定复选框的选择或两个复选框均未选中的情况,需要执行更多不同的任务。 我已经实现了这一点,并且在选中一个复选框或两个都未选中时执行任务时遇到问题
<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')
}
}
关于angular - 一次只选择一个复选框并在选中的特定复选框或未选中的两个复选框上执行特定任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55633367/