17 Using and creating pipes

 

This chapter covers

  • Creating and applying pipes
  • Using pure and impure pipes to update HTML content
  • Formatting data values using the built-in Angular pipes

Pipes are small fragments of code that transform data values so they can be displayed to the user in templates. Pipes allow transformation logic to be defined in self-contained classes so that it can be applied consistently throughout an application. Table 17.1 puts pipes in context.

Table 17.1. Putting pipes in context
Question
Answer
What are they?
Pipes are classes that are used to prepare data for display to the user.
Why are they useful?
Pipes allow preparation logic to be defined in a single class that can be used throughout an application, ensuring that data is presented consistently.
How are they used?
The @Pipe decorator is applied to a class and used to specify a name by which the pipe can be used in a template.
Are there any pitfalls or limitations?
Pipes should be simple and focused on preparing data. It can be tempting to let the functionality creep into areas that are the responsibility of other building blocks, such as directives or components.
Are there any alternatives?
You can implement data preparation code in components or directives, but that makes it harder to reuse in other parts of the application.

Table 17.2 summarizes the chapter.

17.1 Preparing the example project

17.2 Understanding pipes

17.3 Creating a custom pipe

17.3.1 Registering a custom pipe

17.3.2 Applying a custom pipe

17.3.3 Combining pipes

17.3.4 Creating impure pipes

17.4 Using the built-in pipes

17.4.1 Formatting numbers

17.4.2 Formatting currency values

17.4.3 Formatting percentages

17.4.4 Formatting dates

17.4.5 Changing string case

17.4.6 Serializing data as JSON

17.4.7 Slicing data arrays

17.4.8 Formatting key-value pairs

17.4.9 Selecting values