Follow by Email

Angular 2 - Directives and pipes


What are directives?

In Angular, a component is actually a directive with a template. Directives provide functionality and can transform the DOM. 



There are two types of directives:
a)      Structural
  Structural directives modify layout by altering elements in the DOM. 

b)      Attribute. 
Attribute directives change the behavior or appearance of an existing DOM element. 

Since directives do not have a template, they are something you can create with the intent of applying them to an existing element, or in some cases a template element to change that element in some way. Like a component, a directive gets configured with a selector that Angular will use to find a match and apply the directive. 

You apply a directive in different ways. You can write an attribute on an element that matches your selector. Or you can use the template syntax to add a directive in an assignment statement.



 In addition to creating your own directives, Angular comes with a number of directives out of the box to handle common web app constructs, like conditionally rendering elements based on some expression, looping out items to render, or even for things like router links.





What are Pipes?

Another tool in the Angular toolbox to display content is the pipe. A pipe takes end data, like a string or an array, and runs some logic to transform it to a new output. 

Angular comes with some common pipes, like date in upper case and lower case. You can also write your own pipes to handle custom scenarios that fit your application needs. Pipes are a great way to change data in a reusable way without having to embed the transform logic within component classes, and without having to modify the data just for display purposes.