Search code examples
angular

Grammatically correct plural / singular endings


Using a for loop, I have created a counter for late items by looping through items retrieved in a web request, setting a property of late as true if conditions are met, and incrementing the counter.

Using *ngIf, I could do the following:

<h5 *ngIf="lateCount != 1">You have {{lateCount}} late items.</h5>
<h5 *ngIf="lateCount == 1">You have {{lateCount}} late item.</h5>

Is there a way to do this without two *ngIfs?


Solution

  • You can use NgPlural:

    <h5>
      You have {{lateCount}} late
    
      <ng-container [ngPlural]="lateCount">
        <ng-template ngPluralCase="=1">item.</ng-template>
        <ng-template ngPluralCase="other">items.</ng-template>
      </ng-container>
    </h5>
    

    Original answer (before NgPlural)

    Well you can trigger only s symbol on condition:

    <h5>You have {{lateCount}} late item<ng-container *ngIf="lateCount == 1">s</ng-container>.</h5>
    

    Another approach would be to write a pipe that does this for you, or furthermore, you can use Angular i18n (any other library) that provides the functionality to work with pluralization.