Author avatar

Gaurav Singhal

Using a Custom Directive

Gaurav Singhal

  • Dec 5, 2019
  • 5 Min read
  • 19 Views
  • Dec 5, 2019
  • 5 Min read
  • 19 Views
Languages Frameworks and Tools
Angular

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.

1
ng g d demo --skipTests=true
console

Or

1
ng generate directive  --skipTests=true
console

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.

1
2
3
4
5
6
7
8
import { Directive } from '@angular/core';

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

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:

1
<div appDemo></div>
html

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:

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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'
  }

}
ts

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

1
<div appDemo>Custom Directive Demo</div>
html

Output:

Output screenshot

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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")
  }

}
ts

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:

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

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.

0