要根据给定的数组 [“1000”, “1001”, “1000”, “1001”, “1010”, “1000”, “1001”],将每个元素拼接 dataRoles 作为控件名(如 “1000_dataRoles”),并使用 this.roleFormGroup.addControl() 动态添加 FormControl,可以这样实现:
- 定义动态控件名并添加 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);
- 完整示例(结合递归获取叶子节点)
如果要从原始树结构 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);
}
- 结果验证
假设输入树结构和 dataRoles 后缀,最终生成的控件名如下:
1000_dataRoles
1001_dataRoles
1010_dataRoles
...
表单的 value 结构会类似:
{
"1000_dataRoles": [],
"1001_dataRoles": [],
"1010_dataRoles": [],
...
}
- 注意事项
避免重复添加:用 if (!this.roleFormGroup.get(controlName)) 防止重复添加同名控件。
初始值:new FormControl([], []) 表示初始值为空数组,无同步校验器。
动态表单更新:如果后续需要删除控件,用 this.roleFormGroup.removeControl(controlName)。
类型安全:建议为 roleFormGroup 定义类型:
interface RoleFormGroup {
[key: string]: FormControl<any>; // 动态键名
// 其他固定控件...
}
- 扩展:批量设置控件值
如果需要为这些动态控件设置默认值(如 [‘1’, ‘4’]):
leafKeys.forEach(key => {
const controlName = `${key}_dataRoles`;
this.roleFormGroup.get(controlName)?.setValue(['1', '4']);
});