1

I am going through the Angular pipes but facing difficulty understanding the advantage of pipe over common function.

Does Angular treats Pipes differently then functions? If yes, then what is stopping Angular to treat functions also like pipes? why we need to seperately define pipes?

For example, if I have a function that converts to uppercase letter, does this just not enough to define that function? Do I need to comeup with Pipe?

Whatever the benefits Angular is giving to pipes it can give to this function also right without defining it as pipe?

user2225190
  • 547
  • 1
  • 6
  • 18

1 Answers1

1

You are right, Angular pipes are basically just functions. The problem they solve is that functions are generally not available to your templates without first attaching them to the scope of the component via a public field. This means that everywhere you would like to use a function in your template, you would need to add it as a public field to your component.

If you define a pipe as part of an Angular module and then import that module, the pipe will be available in all templates for components declared by the importing module. It also makes it much easier to build out a library of common pipes and share them as an npm package. You do not have to ask the consumers of your library to add them to their component's public interface just for the functions to be useful.

Edit: There are also performance implications as referenced by @Eliseo's comment below

mortalapeman
  • 1,415
  • 12
  • 16
  • well, a function in the .html will be executed several, several times, but *pupe* pipes not, see this [SO](https://stackoverflow.com/questions/48332039/methods-vs-pipes) – Eliseo Apr 19 '23 at 06:39
  • @Eliseo great point, I hadn't considered the performance implications. I pretty much only ever use the `async` pipe and just do all my code transformation before it even gets to the template, so I had completely forgotten about that aspect. – mortalapeman Apr 19 '23 at 20:49