Angular 自定义管道以获取复选框中的项目数

Angular custom pipe to get number of items in checkbox

我正在计算已选中复选框的数量。为此,我添加了一个自定义管道:

import { Pipe, PipeTransform, Injectable, ElementRef } from "@angular/core";
@Pipe({
  name: "getSelected",
  pure: false
})
@Injectable()
export class GetSelectedCountPipe implements PipeTransform {
  constructor(private hostElement: ElementRef) {}

  transform(items: any[]): any {
    // take out only selected values
    if (this.hostElement && this.hostElement.nativeElement) {
      const result = items.filter(item => item.selected === true).length;
      return result.toString();
    }
  }
}

你应该return string在要绘制的管道中,如下面的Demo

https://stackblitz.com/edit/angular-iaswzg

TS:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'getSelectedCount',
})
export class GetSelectedCountPipe implements PipeTransform {
  transform(items: any[]): number {
    return items.reduce((previousValue, currentValue) => {
      return previousValue + (currentValue.selected ? 1 : 0);
    }, 0);
  }
}

请注意,我已删除 @Injectable() 并将 filter 更改为 reduce

HTML:

<span style="white-space: nowrap;">Total: {{ ARRAY | getSelectedCount }}</span>

PS:不要忘记将 @Pipe 添加到 @NgModule#declarations.