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



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

<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>

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

期望的结果是最终得到我可以做到的东西:

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

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

您可以编写一个简单的指令来完成这项工作。在堆栈闪电战上检查此重现。它只计算 12 个div 中的 2 个,因为只有在创建div 时才会触发指令。以下是代码,以防堆栈闪电战不起作用:

应用:

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;
} 
}

应用.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将完成这项工作。