我有一个对象数组,我想将其用作表单控件,作为复选框列表。如果选中了复选框,则将复选框值添加到表单控件(列表,开始为空)。这是我到目前为止的内容:
userAddForm = new FormGroup({
firstName: new FormControl('', [Validators.required,
Validators.minLength(4)]),
lastName: new FormControl('', [Validators.required,
Validators.minLength(4)]),
email: new FormControl('', [Validators.required,
Validators.email]),
username: new FormControl('', [Validators.required,
Validators.minLength(4)]),
password: new FormControl('', [Validators.required,
Validators.minLength(5)]),
});
组件初始化后,我实例化数组并从数据源构建它,然后我想我必须这样做:
this.userAddForm.addControl(this.locations);
但是我该如何在模板中完成这项工作?
答案 0 :(得分:-1)
您可以从代码中提供stackblitiz吗?
您可以尝试将复选框的表单控件绑定为:
bindCheckBoxGroup(array) {
const group = [];
const group1 = [];
array.map((l) => {
group1.push(new FormGroup({
key: new FormControl(l.name),
value: new FormControl(l.name.toLowerCase()),
status: new FormControl(l.value),
}));
});
const formControlArray = new FormArray(group1);
group.push(new FormGroup({
options: formControlArray,
selectedOptions: new FormControl(UserService.mapItems(formControlArray.value)),
}));
formControlArray.valueChanges.subscribe((v) => {
group[0].controls.selectedOptions.setValue(this.mapItems(v));
});
return group[0];
}
mapItems(items) {
const selectedItems = items.filter((l) => l.status).map((l) => l.key);
return selectedItems.length ? selectedItems : null;
}