Introduction to Pipes

Understand why pipes are useful in Angular projects.

We'll cover the following

Welcome to the second part of this course, which covers pipes in Angular. We’ll learn how pipes can help us, how to use built-in pipes in Angular, and how to create custom pipes for our project. Later, we’ll discuss pipes, both built-in and custom, in more detail. We’ll also strengthen our learning through guided exercises. Then, we’ll summarize everything at the end in the form of a cheat sheet.

What is a pipe?

A pipe is simply a function dedicated to transforming a value from one form into another. Because of their function, pipes are commonly used in templates. However, they can also be used in component classes.

Here are a few advantages of pipes:

  • Pipes provide a way to unify output values across the entire application so that they are displayed to the user in the same way.
  • The transformation logic is encapsulated into a single file and then reused in various places.
  • By default, pipes run transformation logic only when input data changes, making the concept highly performant.

Examples of use

Before we define pipes formally and learn how to apply them, let’s go through a simple example to see how they work.

Let’s imagine an application where there are a lot of views that display dates. It could be a calendar or a timer application, for example. Dates can be displayed in various formats. They can include weekdays, months, or just plain digits. There are many possible combinations. Some of them are related to the user’s locale. For example, in some regions, we want to display months first in the MM/DD/YYYY format, while in others, we display days first like DD/MM/YYYY.

Most likely, we want to keep the format consistent across our entire application while accounting for the user’s region. Obviously, we could introduce some format logic and duplicate it through all components that display the date. However, this isn’t a good idea because at some point, we may make a mistake. For example, during a change of requirement, we may forget to update a few places and end up with inconsistent formats.

Introducing pipes could save us from all of this hassle. We can simply use a pipe to get the date that we need to display, apply some transformation logic to it, and return the consistent format. Then we’ll use that same pipe everywhere, completely solving the code duplication issue!

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy