Introduction
Directives are used a lot in an Angular application. But what are directives? Directives simply put, are functions that the Angular compiler runs when it finds them in the DOM. Directives give developers more tools when writing HTML markup.
Built-in directives
Angular comes with built-in directives. Some examples of these built-in directives are: NgIf
which you can use as an if statement in your template file. Another is NgFor
which also can be used in your template file in order to loop over a data structure.
How to create a directive
In order to create a directive type the following in the root directory of the project use the Angular CLI:
ng g d NameOfDirective
g
stands for generate
d
stands for directive
Attribute directives
Attribute directives change how the DOM looks and behaves. They can be used to apply styles conditionally to elements or change how a component behaves based on the change of a property. For example, if you have a data table and you want to highlight values in a certain colour for rows that fall in a certain range that you have set, you can use attribute directives for that.
Structural directives
Structural directives are used in the creation and destruction of elements in the DOM. For example, the hidden
attribute directive is used in either showing or hiding elements in the DOM. The DOM remains as it is. With structural directives elements are either added to the DOM or removed from the DOM, thereby changing the structure of the HTML document.
Conclusion
Directives are a very powerful feature in Angular. They give the capability of writing code once and applying them in any template across your application. Hopefully this post has clarified what directives are and how they can be used.