Pipe Parameters

We'll learn how to use pipe parameters in this lesson.

We’ll look at another pipe defined by Angular called the DatePipe. The DatePipe will help you format dates into various formats. It’s a versatile pipe because we have the freedom to use different formats.

The DatePipe requires the date to be a Date() object, time in milliseconds from 1970, or an ISO string. We must make sure the value is in the required format before we use the DatePipe. Otherwise, it won’t work.

In the app.component.ts file, we’ll create a property called todaysDate. Its value will be a new instance of the Date object.

export class AppComponent {
  name = 'john doe';
  todaysDate = new Date();

In the app.component.html template, we’ll add a <p> tag with the following content:

<p>{{ todaysDate | date }}</p>

By default, this will output the following:

Apr 26, 2020

The output may be slightly different because the date pipe reacts differently based on your environment or when you’re taking this course.

Using pipe parameters

By itself, the DatePipe is capable of formatting the date without our help. It was able to understand the current date because we provided it with an instance of the Date object.

In some cases, we may want the date in a specific format. Since pipes are functions, they have parameters for modifying the behavior of the function. Parameters can be added by adding a colon after the name of the pipe, followed by the value.

The date pipe’s parameter is the format we wish to use for the date. On the documentation page for the date pipe, there’s a section called Custom format options. Here’s a link to the page: https://angular.io/api/common/DatePipe#custom-format-options.

Under the format column, we can use the characters as placeholders for the actual value. The date pipe will take care of replacing the placeholders with the appropriate value. For example, let’s say we want to output only the month and day. We could update the pipe in the template to the following:

<p>{{ todaysDate | date: 'MMMM d' }}</p>

This will output the following:

April 26

This may be different for some of you, depending on when you’re taking this course.

Predefined date formats

One last thing, in the documentation for the date pipe, there’s a section called Predefined format options. If you don’t feel like setting the format yourself, you can use a predefined set of format options. For example, let’s say we want to use the short format. We could update the expression to the following:

<p>{{ todaysDate | date: 'short' }}</p>

The pipe will still be able to transform the output even though we’re not passing in a format with placeholders. It will notice we want to use one of its inner predefined format options.

For this course, we’ll stick to manually formatting the date ourselves. Here’s the updated code:

Get hands-on with 1200+ tech skills courses.