根据给定的数组动态添加 FormControl

要根据给定的数组 [“1000”, “1001”, “1000”, “1001”, “1010”, “1000”, “1001”],将每个元素拼接 dataRoles 作为控件名(如 “1000_dataRoles”),并使用 this.roleFormGroup.addControl() 动态添加 FormControl,可以这样实现:

  1. 定义动态控件名并添加 FormControl
// 假设这是你的叶子节点 key 数组
const leafKeys = ["1000", "1001", "1000", "1001", "1010", "1000", "1001"];

// 遍历数组,添加控件
leafKeys.forEach(key => {
  const controlName = `${key}_dataRoles`; // 拼接变量名,如 "1000_dataRoles"
  
  // 如果控件不存在,则添加(避免重复添加)
  if (!this.roleFormGroup.get(controlName)) {
    this.roleFormGroup.addControl(
      controlName,
      new FormControl([], []) // 初始值为空数组,无校验规则
    );
  }
});

// 打印结果检查
console.log('动态添加后的表单控件:', this.roleFormGroup.value);
  1. 完整示例(结合递归获取叶子节点)
    如果要从原始树结构 this.nodes 动态获取叶子节点并添加控件:
import { FormGroup, FormControl } from '@angular/forms';

// 递归获取所有叶子节点的 key
getLeafKeys(nodes: any[]): string[] {
  return nodes.flatMap(node => 
    node.isLeaf 
      ? [node.key] 
      : node.children 
        ? this.getLeafKeys(node.children) 
        : []
  );
}

// 动态添加控件
addDynamicControls() {
  const leafKeys = this.getLeafKeys(this.nodes); // 获取叶子节点 key 数组
  leafKeys.forEach(key => {
    const controlName = `${key}_dataRoles`;
    if (!this.roleFormGroup.get(controlName)) {
      this.roleFormGroup.addControl(
        controlName,
        new FormControl([], []) // 初始值空数组,无校验
      );
    }
  });
  console.log('表单控件列表:', this.roleFormGroup.value);
}
  1. 结果验证
    假设输入树结构和 dataRoles 后缀,最终生成的控件名如下:
1000_dataRoles
1001_dataRoles
1010_dataRoles
...

表单的 value 结构会类似:

{
  "1000_dataRoles": [],
  "1001_dataRoles": [],
  "1010_dataRoles": [],
  ...
}
  1. 注意事项
    避免重复添加:用 if (!this.roleFormGroup.get(controlName)) 防止重复添加同名控件。

初始值:new FormControl([], []) 表示初始值为空数组,无同步校验器。

动态表单更新:如果后续需要删除控件,用 this.roleFormGroup.removeControl(controlName)。

类型安全:建议为 roleFormGroup 定义类型:

interface RoleFormGroup {
  [key: string]: FormControl<any>; // 动态键名
  // 其他固定控件...
}
  1. 扩展:批量设置控件值
    如果需要为这些动态控件设置默认值(如 [‘1’, ‘4’]):
leafKeys.forEach(key => {
  const controlName = `${key}_dataRoles`;
  this.roleFormGroup.get(controlName)?.setValue(['1', '4']);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值