Angular 复选框的角度窗体控件数组
我有一个对象数组,我想用它作为窗体控件,作为复选框列表。如果选中复选框,它会将复选框值添加到表单控件(这是一个列表,开头为空)。这就是我到目前为止所做的:Angular 复选框的角度窗体控件数组,angular,checkbox,formgroups,Angular,Checkbox,Formgroups,我有一个对象数组,我想用它作为窗体控件,作为复选框列表。如果选中复选框,它会将复选框值添加到表单控件(这是一个列表,开头为空)。这就是我到目前为止所做的: userAddForm = new FormGroup({ firstName: new FormControl('', [Validators.required, Validators.minLength(4)]), lastName: new FormControl('', [Validators.required, Va
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);
但是,我会在我的模板中做些什么来实现这一点呢 您能从代码中提供stackblitiz吗 您可以尝试将复选框formcontrol绑定为:
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;
}
你能从你的代码中提供stackblitiz吗 您可以尝试将复选框formcontrol绑定为:
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;
}
这是我的评论。没有答案。我无法评论。然后尝试回答问题。这是评论。不是答案。我无法评论。然后尝试回答问题Jasoncat,您需要选择存储“位置”的方式。位置存储在一个字符串数组中,仅包含选定的值?一个布尔真/假数组,与所有可能的位置一样大?用逗号分隔的字符串?然后,您需要选择是否要使用mat multiselect、simples复选框或其他选项。请记住,FormControl可以存储“任何东西”,而不仅仅是数字和字符串,否则数组或对象数组无法显示复选框列表而不是选择输入字段,并且无论何时选中,它都会将其值附加到数组中(如果未选中,则将其从数组中删除)?JasonCat,您需要选择存储“位置”的方式。位置存储在一个字符串数组中,仅包含选定的值?一个布尔真/假数组,与所有可能的位置一样大?用逗号分隔的字符串?然后,您需要选择是否要使用mat multiselect、simples复选框或其他选项。请记住,FormControl可以存储“任何东西”,而不仅仅是数字和字符串,否则数组或对象数组无法显示复选框列表而不是选择输入字段,并且每当选中一个复选框时,它都会将其值附加到数组中(如果未选中,则将其从数组中删除)?