Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Using a Custom Directive

Dec 5, 2019 • 5 Minute Read

Introduction

Hello friends, In this guide, we're going to learn about custom directives. In Angular, directives play an important role. There are many in-built directives like ngClass, ngStyle and so on. But today we're going to make our own directives, i.e., custom directives.

You might find yourself in circumstances where you want a custom directive. Those circumstances can be anything from needing to change the format of a date to checking the email format. After reading this guide, you'll never get stuck trying to do such tasks.

Make A Custom Directive with CLI

You can make a directive without using the CLI. But you need to do some extra work that we can avoid by using CLI to make the directive. There are several commands you can use to make the directive using CLI.

      ng g d demo --skipTests=true
    

Or

      ng generate directive  --skipTests=true
    

In the above commands, I've used --skipTests=true because Angular creates a test file that is used for writing the unit test. We're not going to write any test cases now, so I've skipped that.

Deep Dive Into @Directive Decorator

Now you've successfully created a directive with the name of demo.directive.ts. In this file, you can see a structure like the below snippet.

      import { Directive } from '@angular/core';

@Directive({
  selector: '[appDemo]'
})
export class DemoDirective {
  constructor() { }
}
    

Here Angular adds @Directive, which is imported from @angular/core itself to identify this as a directive. Here you can see a selector attribute, which is written under the pair of square brackets ( [ ] ). It means we can add it in a tag:

      <div appDemo></div>
    

If you want to use it as a className, you can change the selector from '[appDemo]' to '.appDemo'. After this change, you can use it like this:

      <div class="appDemo"></div>
    

Access The Element Using ElementRef

Now you know how to make the custom directive and how to use it in a tag. Now I'm going to explain how you can use that tag into your directive.

So here is the new class which will help you to give a reference to the element. The class name is ElementRef, which is imported from @angular/core. This will give you the reference of that element, and whatever you do that changes dynamically, it will reflect on that element.

This snippet will help you use the ElementRef to change the text color of the element.

demo.directive.ts

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

@Directive({
  selector: '[appDemo]'
})
export class DemoDirective implements OnInit {

  constructor(private element: ElementRef) { }

  ngOnInit() {
    this.element.nativeElement.style.color = 'red'
  }

}
    

In the above code, I'm getting the reference of the element in the constructor. ElementRef is also a wrapper class there; we need to use nativeElement to perform the changes on the element.

Now it's become nothing but a JavaScript. If you're familiar with the DOM manipulation, you can use your DOM manipulation experience at this time.

In JavaScript, we also need to get the element reference by class, tag, or ID name.

app.component.html

      <div appDemo>Custom Directive Demo</div>
    

Output:

You can see the output is exactly the same as what we expected.

If you want to use an event listener as well, use @HostListener. It will work like addEventListener in JavaScript. If you're familiar with addEventListener then It takes less time to understand.

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

@Directive({
  selector: '[appDemo]'
})
export class DemoDirective implements OnInit {

  constructor(private element: ElementRef) { }

  ngOnInit() {
    this.element.nativeElement.style.color = 'red'
  }

  @HostListener('click') onClick() {
    console.log("this item is being clicked")
  }

}
    

In the above code, you can see I've added a click function. After the click of the div element of app.component.htmlin which we've added our own directive, it will display a text on the console.

Output:

      this item is being clicked   demo.directive.ts:15
    

You can see the output text has populated on the console.

Conclusion

Now you're an expert at using custom directives in your projects. So go for it, and if you want to read more about directives, read here.