【发布时间】:2022-02-18 15:58:14
【问题描述】:
我有三个复选框,我想创建一个数组,该数组应该包含选中复选框值的值,并且应该避免推送重复值。
这是我尝试过的,但无论是否选中,值都在推动。
谁能告诉我这里有什么问题?
.ts
public dataSource: any[] = [];
compsForm: FormGroup = new FormGroup({
dataSource: new FormControl('', Validators.required),
name: new FormControl('',Validators.required),
});
dataSourceChange(event:any){
var name = event.target.name;
var isChecked = event.target.checked;
const index = this.dataSource.findIndex((el) => el.id === name);
if (index > -1) {
this.dataSource[index].isChecked = isChecked;
} else {
this.dataSource.push(name);
}
this.dataSource = [...this.dataSource];
console.log(this.dataSource);
}
.html
<form [formGroup]="compsForm">
<input type="checkbox" name="om" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> OM</span>
<input type="checkbox" name="fe" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> FE</span>
<input type="checkbox" name="be" (change)="dataSourceChange($event)" formControlName = "dataSource"> <span> BE </span>
</form>
【问题讨论】:
-
发布您的其余工作(整个组件)。
-
我现在添加了其余的东西 :)
标签: arrays angular typescript checkbox event-handling