How Pipes Work

Let's learn about the basic syntax and features of pipes.

Basic notation and usage

Pipes are classes marked by the @Pipe decorator, just like directives have the @Directive decorator on top of their class.

Here’s an example:

  name: 'myPipe',
export class MyPipe {

Pipes need to be declared in a module that uses these pipes. So, we need to remember to add these into the declaration field of our NgModule:

  declarations: [
export class MyModule {

Pipes usually contain logic that works for the entire application Therefore, it usually makes sense to declare them in the shared module of our Angular application.

How pipes function

Similar to directives, pipes don’t always work the same way. The logic implemented in each pipe varies, but there’s a pattern they all follow.

The essential part is the function in the pipe, which ultimately does all the transformation and generates the output. Let’s look at this example of a simple pipe below:

  name: 'inBrackets',
export class BracketsPipe implements PipeTransform {
	transform(value: string): string{
		return '(' + value + ')'; 

The example presents a pipe that wraps the text value in brackets. So, for instance, when we have a value of 100 and want to wrap it in brackets like this, (100), we can use this simple pipe.

The key observation here is that pipes have to implement the PipeTransform interface, which causes the transform function to be implemented. This is very important because Angular calls this function during runtime to transform data and generate the desired output.

The Transform function

The function transform is a simple function of the pipe’s class. This function must have at least one argument, the input data, and must return a value after the transformation, like this:

Create a free account to view this lesson.

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