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

And*_*rs8 4 angular angular9

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

<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>
Run Code Online (Sandbox Code Playgroud)

显示项目总数很容易,但我还希望能够显示显示了多少以及跳过了多少。如果我可以在循环中有一个“变量++”,那就很容易了。

期望的结果是得到一些我可以做到的:

Total invoices {{blah.length}}
Invoices Shown {{count}}
Invoices not yet due: {{blah.length-count}}
Run Code Online (Sandbox Code Playgroud)

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

Que*_*sel 6

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

应用程序:

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;
  } 
}
Run Code Online (Sandbox Code Playgroud)

应用程序.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>
Run Code Online (Sandbox Code Playgroud)

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

在 html 文件中,我使用索引在显示的 div 上添加条件,您有一个基于其他内容的条件,但它不会改变任何内容。对于跳过的项目数量,很好array.length - this.counter