How to create a custom directive in Angular

The core purpose of directives is to manipulate DOM elements according to the desired output. Angular provides several built-in directives to manage forms, tables, lists, styling, and other template components. It also allows one to define custom directives in projects available throughout the project. It also allows one to define custom directives that are reusable and available throughout the project.

Categories of directives

The directives in Angular are divided into two types:

  1. Attribute directives: These modify the appearance and behavior of existing DOM elements, e.g. [(ngModel)]
  2. Structural directives: These alter the layout of DOM by adding, removing, or replacing the elements. For example, *ngIf and *ngFor are examples of this type of directive.

Components are also directives with the template. No other type of directive has a template. 

How to create a custom directive

The build command, file structure, and declaration of both attribute and structural directives are similar. The only difference is the use of the directive as an attribute in the DOM element. Structural directives start with * when used in a DOM element.

Let us build a custom attribute directive alterBackground to change the background color of the desired element from scratch. The following command can be used to generate a directive in the project.

ng generate directive alterBackground

The command above creates the directive file alterBackground.directive.ts in the Angular project. Use the @Directive decorator to manage a custom directive. Furthermore, AlterBackgroundDirective class is declared for our directive. At this point, we can start writing the code for the background color. Import and add Elementref instance in the constructor to grant access to the DOM element. Also, use the native element property of ElementRef to change the background color of the element as follows:

import { Directive, ElementRef } from "@angular/core";
@Directive({
selector: "[appAlterBackground]"
})
export class AlterBackgroundDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = "yellow";
}
}

To apply the custom directive to a DOM element, add a <h1> tag and introduce appAlterBackground inside the tag. Have a look at the tags in the below app.component.html file.

<div>
<h1 appAlterBackground>Demo text for custom directive</h1>
</div>

Code

The example above of  AlterBackgroundDirective is a beginner-level demo to learn how to create a custom directive. Multiple user events, like mouse enter and inputs, can also be handled in custom directives using @HostListener and @Input tags, respectively. Following is the complete working demo of the above example. We can practice our learning and create other directives in the widget below.

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

@Directive({
  selector: "[appAlterBackground]"
})
export class AlterBackgroundDirective {
  constructor(private el: ElementRef) {
    this.el.nativeElement.style.backgroundColor = "yellow";
  }
}

Explanation

The alterBackground.directive.ts file demonstrates the creation of a custom directive. The file alterBackgroundHandler.directive.ts shows how to handle mouse events and inputs as explained below:

  • Line 9: Use the @Input decorator to pass user inputs as arguments. The alterBackgroundHandler attribute is used in the h1 tag of app.component.html file to show the output.
  • Line 11–15: We have @HostListener as the event handler that responds to the mouse enter and mouse leave events by calling changeBgColor function. We can hover over the output text to observe these handlers.
  • Line 17–18: The changeBgColor function takes color as input and changes the background color of the DOM element to the color provided by @Input decorator.

Copyright ©2024 Educative, Inc. All rights reserved