31

What are the arguments for creating and using directives vs creating and using pipes.

The scenario this question stems from is around currency input and output.

If a user needs to input a currency, why not create/use a directive that parses the input into a formatted currency string? The other option is to take in that string, and display it through a pipe like so:

<input type="text" #val (keydown)="currencyVal=val.value" />
<h3>{{currencyVal | currency}}</h3>

vs

// Where mask-money is a directive that filters the 
//input to a formatted currency string
<input type ="text" mask-money (keydown)="currencyVal=val.value" />
<h3>{{currencyVal}}</h3>

On the other hand, a pipe can be used in the controller/component triggered by an input to filter the value.

I could ask a ton of questions about it, but I basically want to know: what are the arguments for each?

Pezetter
  • 2,783
  • 2
  • 22
  • 40
  • 1
    I'd say the "Angular way" is to use a pipe. Pipes are for formatting data, directives are to alter the behavior/appearance of an element. In your case, you clearly want the former. I don't know if you'll get a lot of "arguments for each case" as this seems like a minor issue. Also, S.O. discourages opinion posts. – AngularChef Jan 31 '17 at 20:20

2 Answers2

68

To bring it to the point in the most simple terms, i would say a pipe is to manipulate data, while a directive is more for DOM manipulation.

A pipe gets data as an input, transforms it and outputs this data in another way.

A directive gets a DOM element it's "attached" to and enhances it with some kind of features.

Of course you will find examples where both make sense (take the Components into account and you have three structure types to decide between) and it's more of a question of preference which you choose.

In your example you would use a pipe. Let's say you want to show the currency value in bold text and use an image-icon as a currency symbol you probably take a directive

malifa
  • 8,025
  • 2
  • 42
  • 57
  • line 2 and 3, that made it so simple for me to understand the difference. Even i was confused when both transform, when to use what. – Raj Mar 27 '21 at 15:19
0

In Angular, pipes, a way to write display-value transformations that you can declare in your HTML. And directives provide functionality and can transform the DOM. The default pipe uses Angular’s ability to pass multiple values into the pipe to get both the value and the default value. A directive is a decorator with no view.

From GeekBoots

Basically the difference as already mentioned is that directives receive DOM elements, and affects them, while pipes receive data and affects it.