The 4 types of Angular Directives

The 4 types of Angular Directives

And how to use them

·

5 min read

Introduction

I got asked in a technical interview what the 4 main types of directives were in Angular and it stumped me. I've obviously heard of and used Directives before such as NgIf or *ngFor but had never really thought about directive 'types'. Thus, this was the inspiration for this article so that you don't find yourself in a situation as I did where I tried to pluck directive types out of my head from thin air.

In this article we will go through the following:

  • What is a Directive in Angular?

  • What are the 4 main types of Directives?

  • How do I use them?

Afterward, you should have a much better understanding of this and be able to both explain and use them in equal measure.


What is a Directive?

Ripped straight from the Angular Documentation directives are "Directives are classes that add additional behavior to elements in your Angular applications." This means they can manipulate the DOM by adding/removing elements, or even changing the look of those elements.

When these directives are found in the DOM by the Angular compiler they are then executed to add to the existing HTML. Angular has built-in directives which come with their own syntax and specific uses and it also has custom directives that you can call what you like!


Types of Directives

The 4 types of directives are as follows:

  • Component directives

  • Attribute directives

  • Structural directives

  • Custom directives

Let's go through these.

Components

This is the most commonly used Directive type and if you've worked with Angular before then you should have heard of it. They are typically written as @Component and come with a selector, templateUrl, and styleUrl. Component directives show us something in the DOM.

Attribute Directives

Attribute directives listen to elements in the DOM and then modify the behavior of those elements in some way. There are three attribute directives:

  • ngClass - adds or removes a class to that element based on if a condition is true or false.

  • ngStyle - sets inline styles for an element based on the state of that component.

  • ngModel - Allows for 2-way data binding of that element.

Let's look at some examples for each.

ngClass

<div>
    <button [ngClass]={'selected' : buttonSelected === 'ONE'}>ONE
    </button>
    <button>TWO</button>
    <button>THREE</button>
</div>

In this example, a class called .selected will be added to the button with the [ngClass] directive when a variable called buttonSelected equals 'ONE'. Then if the buttonSelected property changes to something else, the button element will lose the class .selected.

ngStyle

<div 
  [ngStyle]="item.sale ? {
    background: 'black',
    border: '1px solid red',
    'font-size.px': 16
  }: null">
  ...
</div>

In this example if the property on the item object called sale is true then ngStyle will add the CSS properties to the element within the ternary operator. Otherwise, if it's not true then they don't get added.

ngModel

<input type=text [(ngModel)]=item.name></input>

By using the directive ngModel this means that the input gets updated in the HTML template then this will also update item.name in the ts file and vice versa. This is called two-way data binding and is used a lot particularly in forms.

Structural Directives

Structural directives affect the HTML in some way and can add, remove or modify elements. There are three structural directives:

  • ngIf - element is shown based on whether a condition is true or false.

  • ngFor - loops through an array and generates whatever element this is assigned to for each member of the array.

  • ngSwitch - An element will be shown from a possibility of several based on a switch condition.

If you're familiar with JavaScript then these directives should look familiar and can be thought of like if statements, for loops or switch statements.

Time for some examples.

ngIf

<div *ngIf="!loading">
    Content
</div>

<div *ngIf="loading">
    Loading...
</div>

Pretty simple, if the boolean expression loading is true then the 2nd div will show and if it's false then the first one will show instead.

ngFor

<ul>
    <li *ngFor="let item of items">
        {{item.name}}
    </li>
</ul>

Much like a for loop, this directive will loop through an array, in this case items, and produce an <li> for each one.

ngSwitch

ngSwitch is a little bit more involved but acts just like a switch statement, here's a reminder as to what one of those looks like.

switch(carType) {
    case 'Honda':
        return 'Honda'; 
    case 'Peugeot':
        return 'Peugeot'; 
    default: 
        return null;
}

It's like a big if/else block that returns whichever case the argument in the switch statement matches. So now if we look at the ngSwitch.

<div [ngSwitch]="carType">
    <div *ngSwitchCase="'Honda'">Honda</div>
    <div *ngSwitchCase="'Peugeot'">Peugeot</div>
    <div *ngSwitchDefault>Where's my car?</div>
</div>

As you see this follows the same structure as the switch statement above it with its ng equivalent replacing switch, case, and default.

Hopefully, now you have a much better understanding of Directives. There is one more type which is custom directives.

Custom directives are directives that you can create to do pretty much whatever you want! It's beyond the scope of this article to explain how to create one but for some further reading then this article is a good start.


Conclusion

And that's directives! Anybody using Angular as their front-end framework of choice will use these regularly so it's a good idea to get comfortable with them.

Happy coding!