【问题标题】:How to make checked box value as true in reactive forms using angular8如何使用 Angular 8 在反应形式中将复选框值设为 true
【发布时间】:2020-05-07 12:38:34
【问题描述】:

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

演示:DEMO

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

【问题讨论】:

  • 首先,这不是反应形式。此外,您的演示无法正常工作,您在那里缺少 onChange 功能。还有printLists是什么?
  • 是的,我在很多地方都犯了错误,我没有从哪里得到改变,我尝试使用反应形式,但都没有工作
  • 能否请您准确说明问题所在。至少我很难理解。问题出在哪个数组?
  • 我已经更新了我的演示,在这里我想要 2 个条件起作用,1) 当点击选择/取消选择时,它会被选中和取消选中,但是如果我取消选中任何一个复选框,选择/取消选中框仍在检查中
  • 2) 如果我取消选中任何值并控制它,我仍然会得到该特定项目的错误值。我的意思是真/假值没有更新

标签: angular forms checkbox reactive


【解决方案1】:

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

在迭代中:

<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

【讨论】:

  • 如果我没有选择/取消选择框,如何处理?
  • 您所说的“已处理”是什么意思。如果您不希望全选/取消全选,那么只需将其删除?它不会影响其余代码:)
  • 我的意思是,如果我删除那部分代码,那么更改事件不起作用?
  • 我希望你能在我的演示链接中了解,我已经删除了选择/取消选择部分本身。所以想知道它如何与所选项目值一起使用以及数据如何与该 id 一起使用
  • 好吧,就像我说的那样,只需从我的 stackblitz 中删除复选框并在迭代中将 $event.target.checked 分配给print.valuestackblitz.com/edit/angular-haewdd?file=src/app/…
【解决方案2】:

我已更改您的Stackblitz Demo解决改进它。
您应该在change 方法的Select/Deselect all 选项中使用formArraypatchValue

https://stackblitz.com/edit/angular-gt5kkc?embed=1&file=src/app/app.component.html

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2017-08-26
    • 2020-02-29
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2017-11-13
    • 2019-11-09
    相关资源
    最近更新 更多