How to Create & Use Custom Directive In Angular

In this tutorial, we will show you how to create a Custom Directive in Angular. The Angular directives help us to extend or manipulate the DOM. We can change the appearance, behavior, or layout of a DOM element using the directives. We will build a four directive example s and show you how to

  1. Create a custom directive using the @Directive decorator.
  2. We will create both custom attribute directive & custom Structural directive.
  3. How to setup selectors
  4. Pass value to it using the @input.
  5. How to respond to user inputs,
  6. Manipulate the DOM element (Change the Appearance) etc.

Angular Directives

The Angular has three types of directives.

  1. Components
  2. Structural Directives
  3. Attribute Directives

Components are directives with Template (or view). We know how to build Angular Components. Structural & Attribute directives do not have an associated view.

Structural directives change the DOM layout by adding and removing DOM elements. All structural Directives are preceded by the Asterix (*) symbol.

The Attribute directives can change the appearance or behavior of an element.

Creating Custom Attribute Directive

The Angular has several built-in attribute directives. Let us create a ttClass directive, which allows us to add class to an element. Similar to the Angular ngClass directive.

Create a new file and name it as tt-class.directive.ts. import the necessary libraries that we need.

Decorate the class with @Directive. Here we need to choose a selector (ttClass) for our directive. We name our directive as ttClassDirective.

Our directive needs to take the class name as the input. The Input decorator marks the property ttClass as the input property. It can receive the class name from the parent component.

We use the same name same as the select name ttClass. This will enable us to use the property binding syntax <button [ttClass]="'blue'"> in the component.

You can also create more than @Input properties.

We attach the attribute directive to an element, which we call the parent element. To change the properties of the parent element, we need to get the reference. Angular injects the parent element when we ask for the instance of the ElementRef in its constructor.

ElementRef is a wrapper for the Parent DOM element. We can access the DOM element via the property nativeElement. The classList method allows us to add the class to the element.

The complete code is as shown below.

In the app.component.css and the CSS class blue

Finally in the component template attach our customer directive ttClass to the button element.

You can see from the image below, that class='blue' is inserted by Our Custom Directive.

Custom Directive Example in Angular
Custom Directive Example in Angular

The above is a simple imitation of ngClass. Have a look at the source code of ngClass

Creating Custom Structural Directive

Now, let us build a Custom Structural directive. Let us mimic the ngIf and create a custom directive, which we name it as ttIf. There is hardly any difference in creating a Attribute or structural directive.

We start of with creating a tt-if.directive.ts file and import the relevant modules.

Decorate the class with @Directive with the selector as (ttIf). We name our directive as ttIfDirective.

A variable to hold our if condition.

Since, we are manipulating the DOM, we need ViewContainerRef and TemplateRef instances.

Our directive needs to take the if condition as the input. The Input decorator marks the property ttIf as the input property. Note that we are using setter function, because we want the add or remove the content whenever the if condition changes.

We use the same name same as the select name ttIf. This will enable us to use the property binding syntax <div *ttIf="show"> in the template.

This is where all the magic happens. We use the createEmbeddedView method of the ViewContainerRef to insert the template if the condition is true. The clear removes the template from the DOM.

That it. Remember to ttIfDirective in the declaration array of the app.module.ts. The complete code is as shown below.

Component class

Template

Run the app and compare the ngIf & our custom directive ttIf side by side.

Angular Custom Directive ngIf Clone

Why you need to specify *

Remove the * from our newly created ttIf directive. And you will get the error message

ERROR NullInjectorError: StaticInjectorError(AppModule)[NgIf -> TemplateRef]:
StaticInjectorError(Platform: core)[NgIf -> TemplateRef]:
NullInjectorError: No provider for TemplateRef!

We use the *notation to tell Angular that we have a structural directive and we will be manipulating the DOM. It basically tells angular to inject the TemplateRef. To inject the templateRef, the Angular needs to locate the template. The * tells the Angular to locate the template and inject its reference as templateRef

Custom Directive Examples

The following two more Custom Directive Examples. Toggle & Tooltip directives

Toggle Directive

The following directive adds or removes the CSS class toggle from the Parent element. We do that by listening to the click event on the host element or parent element.

Angular makes this easy to listen to the events from the parent or host element using the@HostListener function decorator. We use it to decorate the function (onClick method in the example). It accepts the name of the event as the argument and invokes the decorated method whenever the user raises the event.

The complete code of the ttToggleDirective is as follows.

Add the following CSS Class

Use it as follows.

Toggle Directive Example

Tooltip Directive

The tooltip directive shows the tip whenever the user hovers over it. The directive uses the HostListener to listen to the mouseenter and mouseleave events.

The showHint method adds a span element into the DOM and sets its top & left position just below the host element. The removeHint removes it from the DOM.

Add the following CSS Class

Use it as follows.

Tootip Directive Example

References

  1. @Directive decorator
  2. ngClass Source Code
  3. Directives Source Code

2 thoughts on “How to Create & Use Custom Directive In Angular”

  1. There is one missing step at the end of *Creating Custom Attribute Directive* (the author mentions it in the next section though).
    Simply creating the directive won’t work, it needs to be declared in app.module.ts in the @NgModule > declarations like so:

    @NgModule({
    declarations: [
    AppComponent,
    ttClassDirective
    ],
    ...
    })

    You might need to save the html file again to see the changes on your preview.

    (Other subject)
    I had an issue where the tooltip wouldn’t appear. After debugging, I found that I had left a link to bootstrap.min.css in app.component.html which has its own .tooltip class. Renaming our custom tooltip class from tooltip to tt-tooltip fixed the issue.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top