DEV Community

Cover image for Angular Directives in 5 minutes

Posted on


Angular Directives in 5 minutes

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.


This directive conditionally shows content based on an expression's value.



Alt Text

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"

Alt Text

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.

Alt Text


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


Plain syntax:
[ngStyle]="{style: expression}"

In this case, we bind it directly to a property in our logic. So our div will be red.

Alt Text


This directive allows us to set classes dynamically to our elements.
[ngClass]="{cssClass: expression}"

Alt Text

Alt Text

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)

danytulumidis profile image
Dany Tulumidis

Nice article! Was a nice refresher 😁