Learn Angular 4 Directives


If you missed our last Angular post please check it out here.

Some Angular 4 directive examples will go beyond the scope of this post but be sure to check out this awesome Angular book by Nathan Murray for additional Angular 4 directive information.

Not much has changed in terms of directives for Angular 4 so this post will be a general directive overview mentioning Angular 4 directive changes where appropriate.

Under the hood, a directive in Angular is just a plain JavaScript class that is decorated with the @directive decorator. In Angular, we have 3 different types of directives.

These are:

  • Component Directives
  • Structural Directives
  • Attribute Directives

An attribute directive tends to change the look and behaviour of an element. Whereas a structural directive will manipulate the DOM and add or remove elements depending on what action the structural directives apply.

An Angular 4 Component Directive uses the shadow DOM to create encapsulated visual behaviour that is typically used to create UI widgets.

Angular 4 Attribute Directives

We will start with attribute directives and how this interacts with our DOM and data.

We can also differentiate a component from a Angular 4 directive using this handy table provided for here.

You can create your own Angular 4 attribute directives or you can use Angular’s built in directives.


ngClass Directive

A fairly simple illustration of a basic attribute directive, ngClass is added into our component element and its value is given as a class.

import {Component, CORE_DIRECTIVES} from 'angular2/angular2'

  selector: 'my-app',
  directives: [CORE_DIRECTIVES],
  template: `


string of classes
string of classes
array of classes
object/map of classes
`, styles: [` .gray-border { border: 1px solid gray; } .blue { color: blue; } .green { color: green; } .purple { color: purple; } .active { background-color: #f55; } `] }) export class App { title = "Angular 2 - NgClass"; isActive = false; }

As you can see, we can use the ngClass attribute to assign a class based on styles that we had specified in our styles array.

ngFor Directive

In short, ngFor is a directive that outputs an array element, iterating through each element inside it.

For multiple classes, we can create an array and put those classes inside it to apply to our iterative list. We can then combine this with the aforementioned *ngFor.



{{whiskey.description}} {{whiskey.rating}}

The let key is part of the Angular template syntax. It creates a local variable that can be referenced anywhere in that specific template. let also creates the index i and keeps it as a reference to the current whiskey. All this is done under the hood of this directive.

What if we wanted to style the first and last item in our Angular 4 ngFor directive? This is actually made relatively easy by using let again to assign the first items to variable first and last to variable last.

  • {{ i }} {{ firstItem }} {{ lastItem }} {{ item }}

To be as efficient as possible, ngFor will attempt to not remove and recreate these DOM elements and instead to reuse and recycle when possible. This helps with performance and prevents significant slowdown in our DOM.

ngSwitch Directive

ngSwitch provides us with a structural directive similar to a switch loops in JavaScript and our other Object Oriented language counterparts.

Here is a simple example that combines input button events with ourSwitchCase loop. Based on the number that value returns which is changed depending on which button is clicked, one of the divs with the *ngSwitchCase will be displayed.

  selector: 'my-app',
  template: `
You selected : {{value}}

1. Template - {{value}}
2. Template - {{value}}
3. Template - {{value}}
Default Template
`, }) export class AppComponent {}

ngIf Directive

NgIf adds or removes an element or elements from a sub tree based on the condition specified.

If the expression assigned to ngIf evaluates to a falsy value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

This would be similar to how the display: none property behaves in CSS.

The NgModel directive allows us to provide two way data binding to our HTML element. Whatever we type in the input field will reflect in our name element. In our sample Plunker we had to import and declare our FormsModule in order for this to work. The name attribute should also have the same value as our ngModel.

Creating our own Attribute Directives

I will be going over the fantastic introduction to creating our own Angular 4 directives from Angular University.

We can also create our own custom directives in Angular. In this case, this directive can be applied to any HTML element on the page and will hide this element when it is clicked.

Firstly, we need to import our Angular Directives from Angular core library into your component file.

 import {Directive,ElementRef,Renderer} from '@angular/core';  

We then need to then initialise our directive meta data decorator with the selector property of our choice. In this example its HideElement.


We then want specify the CSS classes that we want to use for the fade out transition.

  opacity: 0;

.element-normal {
  color: #FFFFFF;
  text-align: center;

  -webkit-transition: opacity 3s ease-in-out;
  -moz-transition: opacity 3s ease-in-out;
  -ms-transition: opacity 3s ease-in-out;
  -o-transition: opacity 3s ease-in-out;
  opacity: 1;

And we also need an action to occur when the element is clicked so we will create a function called toggle.

  this.isHidden = !this.isHidden

We than want to use a click event that will trigger the function “Toggle” that will add or remove this fade out css class but we will not be using Angular’s (click) event so how exactly will we accomplish this?

Well, we will use the Angular 4 directive HostListener from Angular Core. Using a Host Listener, Angular will invoke the decorated method (in this case toggle) when the our html element emits the event (when clicked).

In order to access and change properties of the Host Element we must use the HostBinding Decorator. This will check the host binding properties once a change is detected.

For a more detailed explanation of creating your own Angular 4 directives check out this tutorial from Rangle.

If this helped you out be sure to check out our resources page for more recommended reading material on Angular.

Proudly published with Gatsby