These are attributes added to our DOM elements, that make them dynamic. They supercharge ⚡ our DOM by adding extra functionality.
In angular there are two types of directives. Structural and Attribute directives.
Structural directives, change the DOM layout, by adding or removing content. Some examples include *ngIf and *ngFor.
On the other hand attribute directives, change the behavior of an element. Some examples include *ngClass and *ngStyle.
In this post, we will be looking at the most commonly used directives.
This directive conditionally shows content based on an expression's value.
If our expression results in a truthy value, our HTML tag will be rendered. In this case our expression is false, so the p tag will not be rendered
This directive repeats a given DOM element for each element found in an array.
*ngFor="let item of items"
Here our array is the fruits array, and we reference each item in the array as fruit. Then we display it in our component using interpolation.
This directive allows us to add styles dynamically to our tags.
In its simplest form, it is just property binding
We bind the background color of this div to be red
In this case, we bind it directly to a property in our logic. So our div will be red.
This directive allows us to set classes dynamically to our elements.
Directives are powerful, when it comes to handling logic, there is a lot more to directives. We can even create our own custom directives.