DEV Community

loading...
Cover image for Angular Directives in 5 minutes

Angular Directives in 5 minutes

eldrige profile image Eldrige ・2 min read

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:

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

*ngFor

This directive repeats a given DOM element for each element found in an array.

Syntax:
*ngFor="let item of items"

Example:
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

*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

ngStyle

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

*ngClass

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

Alt Text

Result:
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.

Discussion

pic
Editor guide
Collapse
danytulumidis profile image
Dany Tulumidis

Nice article! Was a nice refresher 😁