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 *ngIf
s?
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.
I know this question was asked a lot of time ago, but just to complete the argument there's another way you can accomplish the given task and that's by using the ngPlural
directive.
Primarily ngPlural
directive adds/removes DOM elements based on a numeric values
The ngPlural
directive is very handy and can be used with the Common Locale Data Repository (CLDR) defined category matches such as: one, few or many. As from the angular documentation you can use the directive as follows:
<some-element [ngPlural]="value">
<ng-template ngPluralCase="=0">there is nothing</ng-template>
<ng-template ngPluralCase="=1">there is one</ng-template>
<ng-template ngPluralCase="few">there are a few</ng-template>
</some-element>
For more information about the directive please see ngPlural. Hope it helps :)
I know it's a bit late, but there's a neater way to solve the problem, with pipes.
Here you can learn how to use it, it's really simple and reusable:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'pluralSingular'
})
export class PluralSingularPipe implements PipeTransform {
transform(number: number, singularText: string, pluralText: string = null): string {
let pluralWord = pluralText ? pluralText : `${singularText}s`;
return number > 1 ? `${number} ${pluralWord}` : `${number} ${singularText}`;
}
}
Usage:
{{ someNumberVariable | pluralSingular:'city':'cities }}
As the answer below says you can use NgPlural
Your template should look like:
<h5 [ngPlural]="lateCount">
You have {{lateCount}} late
<ng-template ngPluralCase="=1">item.</ng-template>
<ng-template ngPluralCase="other">items.</ng-template>
</h5>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With