Introducing Directives

Learn what Angular directives are and how to use the ngIf directive in templates.

Angular directives are HTML attributes that extend the behavior or the appearance of a standard HTML element. When we apply a directive to an HTML element or even an Angular component, we can add custom behavior to it or alter its appearance. There are three types of directives:

  • Components: They are directives with an associated template.

  • Structural directives: They add or remove elements from the DOM.

  • Attribute directives: They modify the appearance of or define a custom behavior for a DOM element.

Angular provides us with a set of built-in directives that we can use in our components to cover most use cases. Angular built-in directives are part of the CommonModule. So, we need to import CommonModule when we want to use them.

Note: The Angular CLI imports CommonModule by default when we create a new Angular module, as we learned previously.

We will explore the most popular directives in the following sections.

Transforming elements using directives

The Angular framework includes a set of ready-made structural directives that we can start using straight away in our applications:

  • ngIf: This adds or removes a portion of the DOM tree based on an expression.

  • ngFor: This iterates through a list of items and binds each item to a template.

  • ngSwitch: This switches between templates within a specific set and displays each one depending on a condition.

We will describe each one of them in the following sections.

Displaying data conditionally

The ngIf directive adds or removes an HTML element in the DOM based on the evaluation of an expression. If the expression evaluates to true, the element is inserted into the DOM. Otherwise, the element is removed from the DOM.

Previously, we saw that the product details component was loaded even if there was no product selected. We can now fix that issue by binding the *ngIf directive to a conditional expression in the product-detail.component.html file:

Get hands-on with 1200+ tech skills courses.