How to create custom directive in angular

April 06, 2022

In this article i will explain you how you can create custom directive in angular application, i will create a custom dropdown directive.

Step 1: Create a file for your custom directive

  • Create a file with the name src/directives/dropdown.directive.ts and add the following piece of code

    • First need to import Directive decorator from angular core

    • @Directive is the decorator which tells that class is directive class

    • selector is where we define the name of directive

    • @HostBinding attach property to html element on which directive is applied

    • @HostListener listen to the event of html element on which directive is applied

    • Here we are toggling class open on click of the button that is host listener

import { Directive } from "@angular/core";
  selector: "[appDropdown]",
export class DropdownDirective {
  @HostBinding("") isOpen = false;
  @HostListener("click") toggleOpen() {
    this.isOpen = !this.isOpen;

Step 2: Add the directive declaration inside your component parent module

  • Once we have created the above directive now we need to declare inside app.module.ts or any other module which is the parent module of your current component on which the directive is applied
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";
import { DropdownDirective } from "./directives/dropdown.directive";

  declarations: [AppComponent, DropdownDirective],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent],
export class AppModule {}

Step 3 Use the directive inside your component html

  • I have added the appDropdown directive along with class=“btn-group” html property this is how we attach directive to html element there are also otherways of attaching directive but that depends upon types of directive we are using
<div class="container">
  <div class="row">
    <div class="col-xs-12 ">
      <div class="btn-group" appDropdown>
          class="btn btn-danger dropdown-toggle"
        <div class="dropdown-menu">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Separated link</a>