【问题标题】:ANGULAR - Loop thru ngFor checkboxes and count those that are checkedANGULAR - 循环通过 ngFor 复选框并计算那些被选中的
【发布时间】:2020-12-22 14:40:14
【问题描述】:

我有一个用于 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。

感谢您的帮助。

【问题讨论】:

    标签: angular typescript


    【解决方案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 有很多有用的方法,例如 toggle、deselect、isEmpty、clear 等。

    【讨论】:

      【解决方案2】:

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

      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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-06
        • 2022-03-03
        • 2020-07-16
        • 2016-04-10
        • 1970-01-01
        • 1970-01-01
        • 2011-06-24
        相关资源
        最近更新 更多