【发布时间】:2019-07-25 19:43:27
【问题描述】:
我设法在 UI 上正确绑定了来自 this.empDetails.services 的数据,复选框被正确选中,并且还列出了所有复选框选项。
但是,数据并没有推送到serviceFormArray,当我点击更新而不更改复选框时,this.updateServicesForm.value 为空。
我必须取消选中那些选中的复选框,然后再次选中它,以便它将推送到formarray。
我尝试了一些更改,但无济于事,有人可以建议什么是正确的代码来归档我需要的内容吗?太感谢了。 HTML
<form action="javascript:" [formGroup]="updateSvcForm">
<div class="row" *ngFor="let service of servicesOptions; let i=index">
<div class="col-sm-12">
<div class="checkbox-color checkbox-primary">
<input type="checkbox" id={{service.value}} [value]="service.value" (change)="onCheckChange($event)" [checked]=isSelected(service.value)>
<label for={{service.value}}>
{{service.description}}
</label>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2"></label>
<div class="col-sm-10">
<button class="btn btn-primary m-b-0 ripple light" (click)="updateServices()">Update</button>
</div>
</div>
</form>
Component.TS
sservicesOptions = [
{ description: '1. Sweeping', value: 'sweeping' },
{ description: '2. Mopping', value: 'mopping' },
{ description: '3. Windows', value: 'windows' },
{ description: '4. Washing Clothes', value: 'washingclothes' },
];
this.updateSvcForm= this.fb.group({
sservices: new FormArray([]),
});
onCheckChange(event) {
const sservicesFormArray: FormArray =
this.updateSvcForm.get('sservices') as FormArray;
if (event.target.checked) {
sservicesFormArray.push(new FormControl(event.target.value));
}
else {
let i: number = 0;
sservicesFormArray.controls.forEach((ctrl: FormControl) => {
if (ctrl.value == event.target.value) {
sservicesFormArray.removeAt(i);
return;
}
i++;
});
}
}
isSelected(sserviceOption) {
return this.empDetails.services.indexOf(serviceOption) >= 0;
}
console.log(this.updateSvcForm.value);
}
来自 this.empDetails.services API 的数据返回
sservices: Array(2)
0: "mopping"
1: "washingclothes"
length: 2
__proto__: Array(0)
【问题讨论】:
-
如何填写
this.EmployeeDetails?你能显示更多代码吗 -
只是一个正常的api返回。返回结果如帖子最后部分所示
-
你能说明如何从 api 获取它吗?你在 HTML 中使用
updateServicesForm吗? (是updateSvcForm吗?) -
是的,它的 updateSvcForm。 html中的FormGroupName
-
等待 this.employeeService.getEmployeeDetails(this.Employeeuuid).subscribe((res) => { this.EmployeeDetails = res as Employee[];
标签: javascript angular typescript checkbox