角度 - 循环遍历 ngFor 复选框并计算选中的复选框

时间:2020-12-21 20:14:19

标签: angular typescript

我有一个用于 X 个复选框的 ngFor,如下所示:

<div *ngFor="let child of childrenList; let indice=index">
    <p-checkbox label="{{child.firstname}} {{child.lastname}}" binary="true" (onChange)="dentalChanged(indice, $event)" name="item-{{indice}}">
    </p-checkbox>
</div>

我能够使用以下代码识别何时检查该项目:

dentalChanged(indice: any, event: any): void {
  alert(indice)
  console.log(event.checked)
}

我现在的问题是,我必须在单击按钮时保存所选项目,而且由于 childrenList 上的元素数量是可变的,我不知道如何从 0 到 n。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您可以将选定的值存储在变量中

selectedValues: any[];

dentalChanged(indice: any, event: any, child: any): void {
  if (event.checked) {
    this.selectedValues.push(child);
  } else {
    // you can also use splice and indice to remove child if you dont have any unique property like id
    this.selectedValues = this.selectedValues.filter(c => c.id != child.id);
  }
}

将子项从 html 传递给dentalChanged 方法

<div *ngFor="let child of childrenList; let indice=index">
    <p-checkbox label="{{child.firstname}} {{child.lastname}}" binary="true" (onChange)="dentalChanged(indice, $event. child)" name="item-{{indice}}">
    </p-checkbox>
</div>

答案 1 :(得分:1)

您可以使用 SelectionModel,例如:

组件

  selection = new SelectionModel<any[]>(true, []);
  items = [{ name: "checkbox1" }, { name: "checkbox2" }, { name: "checkbox3" }];

模板

<div>
  <div *ngFor="let item of items">{{item.name}} - <mat-checkbox (change)="selection.toggle(item)"
      [checked]="selection.isSelected(item)">
    </mat-checkbox>
  </div>

  <div>
    Selection count: {{ selection.selected.length}}
  </div>
</div>

SelectionModel 有很多有用的方法,如切换、取消选择、isEmpty、清除等。