首页 > 解决方案 > 如何使用angular8在反应形式中使复选框值为真

问题描述

我已经动态绑定了复选框值。所以现在基于检查和取消检查,我需要传递相同的数据数组,值为真/假。但是现在,即使检查了值,它也只显示假,并且基于检查和取消检查值,如果我取消检查复选框中的任何一个,选择/取消选择仍处于选中状态。

演示:演示

TS:

 checkAll(ev) {
    if (!this.all) {
      this.PrintList.forEach(x => x.value =  true)
      this.isAllChecked()
    } else {
      this.PrintList.forEach(x => x.value =  false)
      this.isAllChecked()
    }
  }

isAllChecked() {
    this.all = !this.all
}

onChange(event, item) {
 if(event){
    this.printLists.push(item);
    } else {
      this.printLists.splice(this.printLists.indexOf(item), 1)
    }
  }

标签: angularformscheckboxreactive

解决方案


如果您想在没有反应形式的情况下执行此操作,这是一种选择。离开了,在基于的迭代中printLists赋值。您可以为全选/取消全选复选框使用 getter,我们也在函数中使用它。因此,基于此,我提出以下建议:print.value$event.target.checkedcheckAll

在迭代中:

<input type="checkbox" [checked]="print.value" (change)="print.value = $event.target.checked" ...>

全选/取消全选复选框:

<input type="checkbox" [checked]="isAll" (change)="checkAll()">

然后是checkAll()函数和getter isAll

checkAll(ev) {
  // check if all are checked or not and act accordingly
  if (!this.isAll) {
    this.PrintList.forEach(x => (x.value = true));
  } else {
    this.PrintList.forEach(x => (x.value = false));
  }
}

get isAll() {
  // return true/false based on if all are checked or not
  return this.PrintList.every(x => x.value === true);
}

你的分叉STACKBLITZ


推荐阅读