1

我有一个对象数组,我想将它们用作表单控件作为复选框列表。如果选中了一个复选框,它会将复选框值添加到表单控件(它是一个列表并且开始为空)。这是我到目前为止所拥有的:

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);

但是,我会在我的模板中做什么来完成这项工作?

4

1 回答 1

0

你能从你的代码中提供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;
  }
于 2019-02-28T16:47:17.227 回答