DEV Community

Tomas
Tomas

Posted on

Declutter your angular template

Problem:
Displaying different messages depending on the number of items in an array can clutter your markup with lots of ngIfs or ngSwitchCases.

Solution:
Utilizing Angular's built in i18nPlural pipe.

Before / Untutored:

Component

count = 0; //0, 1, 2

Template

<span *ngIf="count === 0">You have no cinnamon buns left</span>
<span *ngIf="count === 1">You have one cinnamon bun left</span>
<span *ngIf="count > 1">You have a {{count}} cinnamon buns left</span>

After:

Component

count:number = 0;
bunsLeftMessages = {
   '=0': 'You have no cinnamon buns left',
   '=1': 'You have one cinnamon bun left',
   'other': 'You have # cinnamon buns left'
};

Template

{{ count | i18nPlural:bunsLeftMessages }}

Try it yourself:
https://stackblitz.com/edit/thllbrg-angular-fika-1

Official docs:
https://angular.io/api/common/I18nPluralPipe

Top comments (0)