So what are directives?
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.
*ngIf
This directive conditionally shows content based on an expression's value.
Syntax:
*ngIf="expression"
Example:
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
*ngFor
This directive repeats a given DOM element for each element found in an array.
Syntax:
*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.
*ngStyle
This directive allows us to add styles dynamically to our tags.
Syntax:
In its simplest form, it is just property binding
We bind the background color of this div to be red
Plain syntax:
[ngStyle]="{style: expression}"
In this case, we bind it directly to a property in our logic. So our div will be red.
*ngClass
This directive allows us to set classes dynamically to our elements.
Syntax:
[ngClass]="{cssClass: expression}"
Directives are powerful, when it comes to handling logic, there is a lot more to directives. We can even create our own custom directives.
Top comments (1)
Nice article! Was a nice refresher 😁