【问题标题】:Angular 11 Select All, Deselect All check boxes like GmailAngular 11 全选,取消全选复选框,例如 Gmail
【发布时间】:2021-07-21 14:28:30
【问题描述】:

我正在尝试使用全选和取消全选选项来进行复选框。

我遇到了一个问题,

首先我检查了所有选项(有效),其次我取消选中一个或多个复选框(不是 CheckALL 一个)(这也有效)。最后我检查了所有选项(这不起作用

(当我选择所有选项时(所有复选框都被选中) 当我取消选择所有可以的选项时(所有复选框都未选中))

输出是:

.component.ts 文件

checkedRow = false;
checkedAll = false;
checkedRows = [];


AllSelectedHandler(checked: boolean, book) {
    const idArr = book.map(i => i.id);
    console.log("ID array " + idArr);

    if (checked == true) {
      this.checkedAll = true;
      this.checkedRow = true;

      idArr.forEach(id => {

        if (this.checkedAll == true) {
          this.checkedRow = true;
          console.log("checkedRow works ")
          console.log(this.checkedRow)
        }

        if (this.checkedRows.includes(id)) {
          this.checkedRows.push();
          console.log("if works");
        }
        else {
          this.checkedRows.push(id);
         // this.checkedRow = true;
          console.log("else works");
          console.log("id is " + id);
        }

      });

      console.log(this.checkedRows);
      console.log("checked row" + this.checkedRows);

      const numSelected = this.checkedRows.length;
      console.log("no of selected" + numSelected);
    }
    else {
      this.checkedAll = false;
      this.checkedRow = false;
      this.checkedRows = [];
      this.multipleDelete = false;
      console.log(this.checkedRows);
    }
    const numRows = this.books.length;
    console.log("no of rows " + numRows);
}

.html

<nb-checkbox 
  [value]= "books" 
  [checked]="checkedAll" 
  (checkedChange)="AllSelectedHandler($event, books)" >
</nb-checkbox>
                        
<nb-checkbox 
  value={{data.id}} 
  [checked]="checkedRow"
  (checkedChange)="CheckboxChangeHandler($event, data.id)">
</nb-checkbox>

在控制台中:

ID array 23,22,21,2,1

checkedRow works 
true
else works
id is 23

checkedRow works 
true
else works
id is 22

checkedRow works 
true
if works

checkedRow works 
true
if works

checkedRow works 
true
if works

(5) [21, 2, 1, 23, 22]

checkedrows 21,2,1,23,22

no of selected 5

no of rows 5

这里注意所有的checkedRow 值都是真的。但在输出复选框未选中。

谁能告诉我这是什么问题?

【问题讨论】:

  • 您是否将 id (23, 22, 21, 2, 1) 存储在任何数组中,或者您如何在页面中显示它们(在您的屏幕截图中)?
  • 我将选中的 Id 作为数组存储到 checkedRows 中——这是一个数组。见上面我现在已经编辑了。
  • stackblitz.com上创建一个可运行的代码

标签: angular angular11


【解决方案1】:

您保留第二个数组(例如:selectedItems),就像您正在做的那样,来存储选定的项目。选中一个框时,只需将项目推送到该数组即可。

要全选,只需将原始数组复制到 selectedItems。要取消全选,请将其设置为 [ ]。

然后,当 selectedItems 包含该项目时,只需使复选框显示为选中状态。

在模板中:

...
[checked]="inSelectedItems(id)"
...

在组件中:

inSelectedItems(id: number): boolean {
  return selectedItems.includes(id)
}

这种方式不需要所有的检查和forEach。

【讨论】:

  • 很抱歉没有测试代码或制作项目,如果您发布 stackblitz,我很乐意看看。但我认为这应该很清楚,并且可能会帮助您找到正确的垫子。
猜你喜欢
  • 2016-02-20
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 2011-09-09
相关资源
最近更新 更多