Custom Angular Pipes and Dynamic Locale
Custom Angular Pipes and Dynamic Locale
Support more than one date format with custom pipes
In my last (and first) article I went through how to create an Angular library. This time I will start adding some useful things to it and the first thing I am going to add to it is a couple of custom pipes.
The
If we want to just change from the default en-US
@NgModule({ providers: [ { provide: LOCALE_ID, useValue: 'de-DE' } ] })
You could also be more dynamic and get your locale from a service by using the FactoryProvider.
Remember to register the locale you are going to use with registerLocaleData.
{ provide: LOCALE_ID, deps: [SessionService], useFactory: (sessionService) => sessionService.getLocale()}
But what if we want to be able to change languages in our application? Then we can’t just send the language to our bootstrapping module once and be done with it.
The built-in date and number pipes do accept locale as an argument so we could, in theory, send in a locale that we save in our session and are able to change. And for a smaller app this could be a viable solution.
What I have found works best so far is to create custom pipes that use a locale to format our dates and number. Angular recently (Angular 5?) provided us with formatDate and formatNumber. So it is quite easy now to create our own custom pipes by using these functions.
Implementing Pipes and Session Service
Let's start coding already!An example of how the pipe can look is as follows:
You will also need to register the locale with Angular.Let's create a session service where registerCulture gets called with the culture we want to use.
Another great thing to do that you might not think about is formatting your numbers. This is very similar to the date pipe:
Updating the library
Now we can update the library with our new code and package a new version.
- Add local-date.pipe.ts and local-number.pipe.ts in pipes folder.
- Add session.service.ts in the services folder.
- Export all three added files from public_api.ts.
- Add the pipes to the declarations and exports section in lib-shared.module.ts.
Let's update the version, build and pack our lib-shared to the new version of our library lib-shared-0.0.2.tgz.
libraries> npm version patch --prefix projects/lib-sharedlibraries> ng build lib-sharedlibraries\dist\lib-shared> npm pack
Let's now go over to our other project and install the updated package. Change your version of lib-shared to 0.0.2 and npm install it.
Testing the pipes
Now let's write some code to test our library.
This will let you choose between the Swedish and Norwegian locales. You can press the Norway/Sweden buttons to see how the app dynamically changes the locale.
And that’s it!
Now you can easily import this library to your projects whenever you need to add some local flavor to your app.
In the next article, I will try to improve the development experience by writing some npm scripts to automate all the things.