Angular default pipes and i18n
Sometimes you need to format your template and you don’t want to bother your back end, neither your services in the front end part.
Predefined Pipes are a really good options for fitting your necessities in this case.
You may already know, but if not you must know that there are already exists some default pipes built in Angular
Introduction
The other day I was working in a project in which we have to show currency like X.XXX.XXX,XXX € -> i.e 1.989.674,123 €
Very basic, but interesting for new people learning Angular or for anyone who doesn’t already know how to do it.
And I will teach you how I solve it without touching any code neither in your logic (ts) or services in Front, nor in the Back. Therefore, leave you number & figures to travel along ...
i18n
In computing, internationalization and localization, often abbreviated as i18n means of adapting computer software to different languages, regional peculiarities and technical requirements of a target locale. Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting internationalized software for a specific region or language by translating text and adding locale-specific components…
Code
First of all, for the sake of simplicity we are going to use an already built in pipe to convert our amounts in €
src/app/app.component.html
{{ amount | currency: 'EUR' }}
But, what about if I want to say eyy I am for example in Spain so you should show that like if I were there …
src/app/app.module.ts (I do globally)
...import { registerLocaleData } from '@angular/common';
import localeEs from '@angular/common/locales/es';
registerLocaleData(localeEs);...providers: [
{
provide: LOCALE_ID,
useValue: 'es-ES',
},
],...
That’s were the magic occurs behind the pipe, for more info about registerLocaleData and so on you can browse trough https://angular.io/api/common/registerLocaleData
I leave this little code here, so you can play with it …
Conclusions
Pipes are a good approach to leave your template cleaners, helping us to separate a lot of logic inside them.
With i18n we can see how powerful your code can be working contextually depending on your location.
There are for sure so many ways to achieve that, however I thought it was very interesting to target it from the point of view of i18n and pipes.
Stay on touch, we will see more examples to reduce your code and make your apps more adaptive for your users.