如何在不使用索引或 .length 的情况下计算 Angular 9 ngFor 的迭代次数?

How can one count iterations of Angular 9 ngFor without using index or .length?

我有一个 Angular 循环,其中有条件检查。因此,在数组上使用 .length 或使用索引中的 i 的通常答案不会告诉我有多少项目显示

<form [formGroup]="paymentsForm">
<div formArrayName="arrVoucherLines">  
    <div *ngFor="let line of paymentsForm.get('arrVoucherLines')['controls']; index as i"
     [formGroupName]="i">

     <div *ngIf="dateCheckingConditionalFunctionPlaceholder()">

         <mat-checkbox formControlName='FlagPayInvoice'></mat-checkbox>
         Issued: {{line.value.DateTimeLocalInvoiceIssued |date:'MM/dd'}}
         Due: {{line.value.DateTimeLocalInvoiceDue |date:'MM/dd'}}
        ... variety of other voucer info
    </div>
    </div>
</div>
</form>

显示项目总数很容易,但我还希望能够显示已显示的数量和跳过的数量。如果我可以在循环中有一个 "variable++" 那会很容易。

期望的结果是我能做到的事情:

Total invoices {{blah.length}}
Invoices Shown {{count}}
Invoices not yet due: {{blah.length-count}}

使用案例是用户在表单上选择截止日期,并且只显示该日期之前到期的账单。

您可以编写一个简单的指令来完成这项工作。检查 this repro on stackblitz。它只计算 12 个中的 2 个 div,因为只有在创建 div 时才会触发该指令。这是以防 stackblitz 不起作用的代码:

app.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  array = new Array(12);
  counter = 0;

  addCounter(e:number) {
    this.counter += 1;
  } 
}

app.html:

<div *ngFor="let item of array; let i = index">
    <div *ngIf="i === 3 || i ===4" ngInit (trigger)="addCounter()">
        item {{i}}
    </div>
</div>
<hr>
<div>Total items = {{array.length}}</div>
<div>Generated items = {{counter}}</div>
<div>Skipped items = {{array.length - counter}}</div>

ng-init.directive.ts:

import {Directive, Input, Output, EventEmitter} from '@angular/core';

@Directive({
  selector: '[ngInit]'
})
export class NgInitDirective {
  @Output() trigger: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
    this.trigger.emit();
  }
}

在 html 文件中,我使用索引在显示的 div 上添加了一个条件,你有一个基于其他东西的条件,但它没有改变任何东西。 对于跳过的项目数,array.length - this.counter 就可以了。