Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Directives vs Pipes

Tags:

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?

like image 333
Pezetter Avatar asked Jan 31 '17 20:01

Pezetter


People also ask

What is the difference between directive and pipe in Angular?

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.

What are Angular directives?

Directives are classes that add additional behavior to elements in your Angular applications. Use Angular's built-in directives to manage forms, lists, styles, and what users see.

What are the three types of directives in Angular?

The three types of directives in Angular are attribute directives, structural directives, and components.

What are pipes in Angular?

Pipes are simple functions to use in template expressions to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once.


1 Answers

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

like image 122
malifa Avatar answered Oct 08 '22 06:10

malifa