We should not use methods in the HTML unless they are associated with events:
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:
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):
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 ‘:’:
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 —
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3