Directives

In this lesson, we will look at directives, some commonly used directives, and how we can create custom attribute directives.

`intro-directives

A directive is used when you wish to extend the behavior of any HTML element. It helps us add or extend the behavior of any element in terms of its layout, appearance, etc. In the previous lesson, we created a component directive. A component is also a type of directive, but it has a template of its own.

Directives work the same way we use selectors to reference components.

Angular has the following different types of directives:

  • Component directives, which we have already seen.
  • Attribute directives
  • Structural directives

Attribute directives

These directives help us extend the behavior or appearance of the elements inside the template. The most commonly used attribute directive is NgStyle. This helps you change the style of several elements in one go. We will also look at creating custom attribute directives in Angular later.

Structural directives

These types of directives are most widely used in our Angular apps on a regular basis. These directives help us work on the layout of the data, for example looping through the data, applying conditions on the data, etc. The convention for a structural directive uses an asterisk (*) before the directive name.

The commonly used structural directives are *ngFor and *ngIf.

*ngFor helps us loop through an array and *ngIf helps for the conditional rendering of the data.

Let’s look at both of these in detail.

*ngFor

The *ngFor directive is used in a template to loop through an array. Let’s assume we have an array with the name users, and we want to display its values as a list of items. Let’s see how to do that: Let us see how to do that:

<table class ="table table-striped" >
  <tr *ngFor="let u of users">
    <td>
      {{u.id}}
    </td>
    <td>
      {{u.name}}
    </td>
    <td>
      {{u.model}}
    </td>

  </tr>
</table>

*ngIf

*ngIf is used to display an element based on a condition. This is how it works:

<div *ngIf="showElement">
  <div>This element is based on the showElement condition</div>
</div>

If the value of showElement is true, we will see this div on the view.

Creating directives from the CLI

You can create a directive using the CLI the same way you create a component,

ng generate directive <directive-name>

or the alias

ng g d <directive-name>

This will create two files for you, the directive.ts file and the directive.spec.ts

Get hands-on with 1200+ tech skills courses.