Angular2 Tutorial: Creating Attribute Directives

According to Angular2 documentation, directives are classes that can change the component behavior or/and appearance, which basically means they can add CSS classes and styles, register events and manipulate the component’s properties.

In this tutorial I’m going to show you how to create a very simple directive that will register the click event and add a CSS style to the component. I know we can do this without directives, but keep in mind that this is just an example I’m using to illustrate how directives work.

So let’s jump right into the code:


import { Directive, ElementRef, Input, Renderer } from '@angular/core';
@Directive({ selector: '[showMessage]' })
export class MessageDirective {
    constructor(el: ElementRef, renderer: Renderer) {
       renderer.setElementStyle(el.nativeElement, 'cursor', 'pointer');
       renderer.listen(el.nativeElement, 'click', function(){

As you can see, a directive is just a regular class decorated with @Directive, this decorator allows you to specify a selector, which is the name you’re going to use to call your directive later, in this example the selector is showMessage.

Now let’s take a look at the constructor, to make things easier angular2 is injecting two objects for us: ElementRef and Renderer. The first one allows us to access the DOM element, as the second is used to add/modify its properties.

There are two things I’m doing in this constructor, in the first line I’m using the Renderer’s setElementStyle function to change the cursor style to pointer, and in the second I’m just registering a callback function to the click event.

To make our directive work we also have to declare it in the app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { FormsModule }   from '@angular/forms';
import { MessageDirective } from './message.directive';
  imports:      [ BrowserModule, FormsModule],
  declarations: [ AppComponent, MessageDirective],
  bootstrap:    [ AppComponent ]
export class AppModule { }

That’s it, easy right! Now we can use the directive by just adding its selector to the component as follows:

<p showMessage>Click Here</p>

If you run your application you’ll see that this p element looks like a link, when you click on it the message 'Test' pops up.

Recommended for you

Angular2 Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base e... This is a very common error for Angular2 beginners, if you are reading this it's probably because you're using the RouterModule module for the first time, you've done everything right but when you run your application you see something like this on your firebug: core.umd.js:3462 EXCEPTION: No b...
Creating an Angular2 Datatable from Scratch PART 2: Filtering the Data Continuing from where we stopped at Part 1, today we're going to add the filter functionality to the table, but before we start let's do some styling. I'm going to use Bootstrap, but if you don't want you don't have to, feel free to style your component as you like. But if you decide to use Bootstra...
Angular2: How to Pass Callback Functions to a Component There are lots of situations where it's useful to pass a function to an angular2 component, for instance, when our component is a dialog and we have to perform an specific task when it closes, or pass the action of one of its buttons, or even events like keypress, resize, mouseover, etc. If you're r...
Angular2 Tutorial: Creating Custom Pipes Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don't meet our needs, that's when we have to create custom pipes. This will be a very quick tutorial in which I'll give you an example ...

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>