Improve performance in Angular by creating your CUSTOM PIPES

samirabawad

Samira Awad

Posted on October 2, 2024

Improve performance in Angular by creating your CUSTOM PIPES

We should not use methods in the HTML unless they are associated with events:

Image description

This has the problem of being executed multiple times. In the example, an array is being mapped, which will execute 16 times. Similarly, we should not use get or API requests directly.

This can be solved using a pipe and/or creating a custom pipe, which will only execute once for each user. In this example, the pipe has a transform method that receives the same arguments as the previously used method:

Image description

Image description

Explanation:

The problem with methods arises because they are not native to Angular, so Angular doesn't know when their value has changed. As a result, it keeps constantly evaluating methods for changes after every small update.

In contrast, a pipe is native, pure, and only executes when its arguments change. Additionally, a pipe can be reused in different parts of the application (unlike a method, which can only be reused by sending it to a service).

We can create a pipe if it doesn’t exist by specifying its target location:

ng g p pipes/fullName (where pipes/fullName is the location).

The pipe is created as a class that implements PipeTransform, an interface that requires us to have a transform method. This method is executed when the pipe runs and works just like a normal method. To use the created pipe, we must import it into the app component (standalone):

Image description

When using it in the HTML, we call it by the name indicated in the name field of the pipe, using the ‘|’ symbol followed by the pipe’s name. The first argument is passed to the left, and if we want to pass other arguments, they are passed to the right, after a colon ‘:’:

Image description

Image description

Remember good practices: if there are many arguments, it's better to use an object. As a good practice, try not to overuse pipes to avoid cluttering. Break down the code and you’ll succeed.

To create the pipe's content, we specify the arguments we want to receive and the return type in the transform method. Then, we write the content and return the result. Optional values can be received by prefixing them with a ‘?’, and default values can be assigned using ‘=’.

— Notes based on EfisioDev’s Angular course —

💖 💪 🙅 🚩
samirabawad
Samira Awad

Posted on October 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related