Angular勾选mat-checkbox时如何获取对应categoryId值
Angular 复选框获取CategoryId功能调整方案
现有代码存在的核心问题
- 所有循环渲染的复选框都绑定了同一个
hubxCategoryId表单控件,单个表单控件只能存储一个值,会导致所有复选框状态联动,无法支持多选 - 表单指令拼写错误:模板中写的
formControlname不符合Angular驼峰命名规范,正确写法为formControlName,拼写错误会导致指令完全不生效 - 响应式表单作用域内混用未关联表单的
ngModel指令,Angular 6+版本会直接抛出模板编译错误 - 复选框值获取逻辑冗余,依赖checkbox默认value传值容易出现类型或取值错误
具体修改内容
1. 组件TS代码调整
首先初始化存储选中ID的数组,同时调整表单控件默认值,后续选中状态变化时同步更新表单值即可:
// 组件类内提前声明存储选中分类ID的数组 checkedItems: number[] = []; // 表单初始化逻辑调整 this.patientReportForm = new FormGroup({ patientId: new FormControl(this.clientId), // 多选场景下控件默认值为空数组 hubxCategoryId : new FormControl([]), isTestApproved : new FormControl(), notes : new FormControl(), })
2. 模板代码调整
把表单组绑定挪到循环外层,移除复选框上错误的重复表单控件绑定,调整只读输入框的绑定方式避免ngModel冲突:
<div class="profile-diagnos" [formGroup]="patientReportForm"> <div class="panel-body" *ngIf="hubxReportList.length===0">No records found</div> <div class="example-headers-align"> <div *ngFor="let hubxReport of hubxReportList; let i=index"> <div class="lineheader"> <section class="example-section"> <p> <mat-checkbox color="primary" labelPosition="before" [value]="hubxReport.categoryId" (change)="onChecked(hubxReport.categoryId, $event.checked)"> {{hubxReport.categoryName}} </mat-checkbox> </p> </section> </div> <div class="row paddingTop headerpaddingbottom"> <div *ngFor="let item of hubxReport.hubxDataItems" class="col-sm-4"> <mat-form-field class="example-full-width lineheight25"> <!-- 只读展示不需要ngModel,直接绑定value即可避免表单冲突 --> <input matInput autofocus [placeholder]="item.itemTitle" [value]="item.itemValue" readonly /> {{item.itemUnit}} </mat-form-field> </div> </div> </div> </div> </div>
3. 复选框 change 事件方法调整
直接传入当前分类ID和勾选状态,简化逻辑,增加重复值判断,每次更新选中数组后同步更新表单控件值:
onChecked(categoryId: number, isChecked: boolean){ if(isChecked) { // 勾选时如果数组内不存在当前ID则加入,避免重复存储 if(!this.checkedItems.includes(categoryId)) { this.checkedItems.push(categoryId); } } else { // 取消勾选时移除对应ID const index = this.checkedItems.indexOf(categoryId) if (index !== -1) this.checkedItems.splice(index, 1); } // 同步更新表单控件值,提交表单时可直接通过form.value获取所有选中ID this.patientReportForm.get('hubxCategoryId')?.setValue(this.checkedItems); }
验证方式
操作复选框时,直接打印this.checkedItems或者this.patientReportForm.value.hubxCategoryId就能拿到所有勾选的分类ID数组,符合需求预期。
内容的提问来源于stack exchange,提问作者KingCk
相关产品推荐
相关产品推荐

