Custom Angular Pipes and Dynamic Locale

Support more than one date format with custom pipes.

In my article Get Started with your first Angular Library 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 DatePipe in Angular is great, but if you want to be able to support more than one language in your application you might want to implement your own pipe. In this article, I will show how to register your locales, create your custom pipes and then we will add them to our library.

If we want to just change from the default en-US locale we can do it in our app.module.ts.

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.