Menu

Angular NgPlural Directive for Localization

February 22, 2017 by Christopher Sherman

The Angular ngPlural directive adds or removes DOM templates based on a numeric value. It comes in handy when you’re doing localization (l10n) to adapt your content to meet the language and cultural requirements of a specific market.

When you want to use the plural rules, enter the plural category in the ngPluralCase directive. When you want an exact match, such as “4” in the example below, use the equal sign before the value in the ngPluralCase directive.

<p>
 I have {{count}} items, but I could also say 
 
 <span [ngPlural]="count">
 <template ngPluralCase="zero">there are no items.</template>
 <template ngPluralCase="one">there is one item.</template>
 <template ngPluralCase="two">there are a couple items.</template>
 <template ngPluralCase="few">there are a few items.</template>
 <template ngPluralCase="=4">there are four items.</template>
 <template ngPluralCase="many">there are many items.</template>
 <template ngPluralCase="other">there are some items.</template>
 </span>
</p>

Looking at the Angular localization source code, some languages, such as English, have limited plural localization (only “one” and “other”). Other languages, such as Welsh, have the full gamut of Unicode plural rules. To make for a more interesting example, I configured my Plunker example to use the Welsh language.

You can navigate to the src/app.ts file in Plunker to adjust the count property. Adjust the LOCALE_ID at the bottom of the same file if you want to change the locale.

Angular JavaScript