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

Angular动态FormArray中如何实现is_primary_contact_number复选框单选功能

Angular FormArray 主联系电话单选实现方案

实现逻辑

通过监听主联系电话复选框的变更事件,当某一行被勾选为主号码时,自动清空其他行的主号码勾选状态,保证同一时间最多只有一个主号码。

步骤1:修改组件类代码

在原有的AppComponent类中新增两个方法:主号码切换处理方法、联系人删除方法:

// 主联系电话切换触发
public onPrimaryToggle(selectedIndex: number): void {
  const currentControl = this.getFormGroup(selectedIndex).get('is_primary_contact_number');
  const isChecked = currentControl.value;
  // 只有当前是勾选状态时,才重置其他行的勾选状态
  if (isChecked) {
    this.contacts.controls.forEach((group, index) => {
      if (index !== selectedIndex) {
        // emitEvent设为false避免循环触发变更事件
        group.get('is_primary_contact_number').setValue(false, { emitEvent: false });
      }
    });
  }
}

// 删除联系人行
public removeContact(deleteIndex: number): void {
  this.contacts.removeAt(deleteIndex);
}

步骤2:修改模板代码

调整复选框绑定

将原有的主号码复选框补充表单绑定和变更事件监听:

<input 
  type="checkbox" 
  class="form-check-input" 
  id="exampleCheck2"
  formControlName="is_primary_contact_number"
  (change)="onPrimaryToggle(i)"
>

补充删除按钮点击事件

将原有的删除按钮补充点击触发逻辑:

<button 
  type="button" 
  class="btn btn-danger float-right" 
  (click)="removeContact(i)"
>
  <i class="fas fa-minus"></i> Remove
</button>

可选优化:调整添加按钮位置

原代码中添加按钮写在*ngFor循环内,会导致每一行都显示一个添加按钮,建议将按钮移到formArrayName所在的div外部,全局只保留一个添加按钮更符合交互逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:18:00