我在 for 循环中有一个复选框,并有一个数组来存储行详细信息。我只想一次选择两个复选框。当用户单击第三个复选框时,应自动取消选中该复选框,同时给出烤面包机消息。
我已尝试实现此操作并成功收到烤面包机消息。但第三个复选框不会自动取消选中。请帮忙解决这个问题。
HTML
<tr *ngFor="let row of rows$; let indexOfEl = index">
<td><input type="checkbox" value="indexOfEl (change)="onCheckboxChange($event,indexOfEl,row)"/></td>
</tr>
TS 文件
onCheckboxChange(event: any, index:any, data: any){
if(event?.target?.checked){
if(this.selectedCommand.length < 2){
data.index = index;
this.selectedCommand.push(data);
}
else {
this.sharedService.showErrorNotification('Cannot select more than two commands', 'Error');
}
}
else this.selectedCommand = this.arrayRemove(this.selectedCommand,index);}
arrayRemove(array:any , index:any){
return array.filter(function(element){
return element.index != index;
});
}
我很快就写出了我将如何做。如果有帮助的话请随意使用。
HTML
<tr *ngFor="let command of commands">
<td>
<input
type="checkbox"
(change)="onCheckboxChange($event, command)"
/>
</td>
</tr>
TS
export class YourComponent {
public selectedCommand: Command[] = [];
public commands: Command[] = [
{ commandName: 'Command 1' },
{ commandName: 'Command 2' },
{ commandName: 'Command 3' },
{ commandName: 'Command 4' },
{ commandName: 'Command 5' }
];
constructor() { }
public onCheckboxChange(event: any, data: Command) {
if (event?.target?.checked) {
if (this.selectedCommand.length < 2) {
this.selectedCommand.push(data);
}
else {
this.sharedService.showErrorNotification('Cannot select more than two commands', 'Error');
event.target.checked = false;
}
}
else {
var indexToRemove = this.selectedCommand.findIndex(x => x.commandName == data.commandName);
this.selectedCommand.splice(indexToRemove, 1);
}
}
}
interface Command {
commandName: string;
}
你可以像这样取消勾选我们还有一种方法 公共 onCheckboxChange(事件:任意,数据:命令){
event.source.checked = false;
}
另一种方式
public onCheckboxChange(事件:任意,数据:命令){
event.target.checked = false;
}