【问题标题】:Angular form control array of checkboxes复选框的角度表单控件数组
【发布时间】:2019-07-22 15:32:45
【问题描述】:

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

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

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

【问题讨论】:

  • JasonCat,您需要选择存储“位置”的方式。位置存储在一个字符串数组中,仅包含选定的值?一个布尔真/假数组,与您所有可能的位置一样大?用逗号分隔的字符串?然后,您需要选择是否要使用 mat-multiselect material.angular.io/components/select/…、simples 复选框或其他。请记住,FormControl 可以存储“任何东西”,不仅是数字和字符串,还有数组或对象数组
  • 他们是否无法显示复选框列表而不是选择输入字段,并且无论何时选中它都会将其值附加到数组中(或者如果未选中则将其从数组中删除)?

标签: angular checkbox formgroups


【解决方案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;
  }

【讨论】:

  • 这是评论。不是答案。
  • 我无法发表评论
  • 然后尝试回答问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 2021-08-26
相关资源
最近更新 更多