Working with Pipes in Angular

In this short tutorial we look at working with pipes in angular. Pipes allow us to transform data. So I have some examples below of using pipes and the different default pipes available. You can also create custom pipes but I’m not going so far. This tutorial continues my dive into angular as I continue to explore the framework.

Continuing using our previous template we want to show the date when the current form is being implemented. To do this we add a date to our component class. The new variable we added is called createdDate.

export class AppComponent {
  title = 'Hello World';
  name = 'Wynton Franklin';
  description = 'This is a description';
  prof = '';
  terms = true;
  cost = 1.00;
  createdDate = new Date();

In our app.component.html we add our html to show the date. Very simple stuff.

<p>Date Created:  {{ createdDate }}</p>

The result is shown below. You can see we get the full date. We don’t want this we want to format the date.

Simple Date in html

To format the date we use pipes. Which is really just the | character.

<p>Date Created:  {{ createdDate | date:"MM/dd/yy"}}</p>

In the code above we add the date pipe with some parameters which determine how the date is displayed. This is great! Now the output we get is formatted as show below.

Formatted date pipe

We could change the format to a more common date format year/month/day. All we have to do is change the parameters on the pipe.

<p>Date Created:  {{ createdDate | date:"yyyy/MM/dd"}}</p>

The results we get are

Formatted date pipe

Lets try another type of pipe. We are going to make the login user totally upper case. To do this we just add the uppercase pipe in our html.

<p>Login User : {{ name | uppercase }}</p>

And just like that we have an uppercase login user.

Uppercase pipe example

We can chain pipes if we need to. In our next example we use the slice pipe and chain it to the uppercase pipe.

<p>Login User : {{ name | slice:0:6 | uppercase }}</p>
Chain a Pipe

Some other cool pipes include

Having fun trying them out and the different options they include.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s