You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Angular FormBuilder将选中复选框值绑定到数组型表单控件

Angular复选框选中值绑定到表单数组控件

要实现将选中复选框的itemId存入itemIds表单控件的数组中,按以下步骤修改代码:

  1. 调整表单控件初始值
    将itemIds的初始值设置为空数组,适配多ID存储需求:

    serviceTaskForm = this.formBuilder.group({
      ...,
      itemIds: [] // 初始化为空数组
    });
    
  2. 实现复选框变更逻辑
    在onCheckboxChange方法中,根据复选框选中状态添加/移除对应ID,同步更新表单控件值:

    onCheckboxChange($event: MatLegacyCheckboxChange) {
      const itemId = $event.source.value;
      const currentIds = this.serviceTaskForm.get('itemIds')?.value || [];
    
      if ($event.checked) {
        // 选中时添加ID,避免重复
        if (!currentIds.includes(itemId)) {
          currentIds.push(itemId);
        }
      } else {
        // 取消选中时移除ID
        const index = currentIds.indexOf(itemId);
        if (index > -1) {
          currentIds.splice(index, 1);
        }
      }
    
      // 更新表单控件的值
      this.serviceTaskForm.get('itemIds')?.setValue(currentIds);
    }
    
  3. 修正模板变量与表单绑定
    模板循环变量为task,需把显示文本的previousTask改为task,同时给表单添加formGroup绑定确保关联:

    <form [formGroup]="serviceTaskForm">
      ...
      <mat-form-field appearance="fill">
        <div class="demo-select-all-checkboxes" *ngFor="let task of tasks">
          <mat-checkbox
            (change)="onCheckboxChange($event)"
            [value]="task.itemId">
            {{ task.itemId }} {{ task.invoice }} 
          </mat-checkbox>
        </div>
      </mat-form-field>
    </form>
    

修改完成后,serviceTaskForm.get('itemIds').value将返回所有选中复选框的itemId组成的数组。

内容的提问来源于stack exchange,提问作者Adoulou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:39:51