How to create a custom directive in Angular

Directives are the fundamental building blocks in Angular used to manipulate and manage the behavior of DOM elements. 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.

Key takeaways:

  • Angular offers three directive types including components, attribute directives, and structural directives.

  • Developers can create custom directives to extend Angular's functionality and manipulate the DOM.

  • Use the @Directive decorator to define a custom directive in Angular.

  • Utilize ElementRef to access and manipulate the host DOM element.

  • Use @HostListener to respond to host element events in custom directives.

  • Employ @Input decorator to accept data from the parent component into the directive.

  • Custom directives promote code reusability and can be shared across components.

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. 

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.

How to create a custom directive

Let us build a custom attribute directive alterBackground to change the background color of the desired element from scratch.

Step 1: Generate a directive in the project

Run the following command to generate a directive in the project.

ng generate directive alterBackground

The above command 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.

Step 2: Modify the directive class

At this point, we can start writing the code for the background color. Import and add the 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";
}
}

Step 3: Apply the custom directive

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 example of using a custom directive

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";
  }
}
An example of a custom directive in Angular

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 the app.component.html file to show the output.

  • Lines 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.

  • Lines 17–18: The changeBgColor function takes color as input and changes the background color of the DOM element to the color provided by the @Input decorator.

Conclusion

Custom directives in Angular are powerful tools for extending the framework’s functionality and creating reusable DOM manipulations. They enable developers to encapsulate complex logic, enhance code reusability, and improve application structure. By using the @Directive decorator, ElementRef, @HostListener, and @Input, developers can create an interactive directives that respond to user events and accept inputs. Whether used for styling, behavior modification, or creating new structural patterns, custom directives are essential for building flexible and maintainable Angular applications. Experiencing custom directives allows developers to unlock the full potential of Angular and create more efficient, modular web applications.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Why use custom directives in Angular?

Custom directives in Angular are used for several reasons:

  • Code reusability: Custom directives allow you to encapsulate DOM manipulation logic that can be reused across multiple components.
  • DOM manipulation: They provide a clean way to manipulate the DOM without cluttering component logic.
  • Behavior extension: Custom directives can extend the behavior of existing HTML elements or Angular components.
  • Separation of concerns: They help in separating the DOM manipulation logic from the component’s business logic.
  • Abstraction: Complex DOM manipulations can be abstracted into simple, declarative HTML attributes.

How to create a custom directive in Angular command?

To create a custom directive in Angular using the Angular CLI, use the following command:

ng generate directive directive-name

or the shorthand:

ng g d directive-name

This command will:

  1. Create a new file directive-name.directive.ts.
  2. Update the app.module.ts file to include the new directive in the declarations array.

What are the three types of directives in Angular?

Angular has three types of directives:

  • Components: These are directives with a template. They are the most common type of directive.
  • Attribute directives: These change the appearance or behavior of an element, component, or another directive.
  • Structural directives: These change the DOM layout by adding and removing DOM elements.

What is custom in Angular?

In Angular, “custom” typically refers to components, directives, pipes, or services that are created by developers to extend Angular’s built-in capabilities. Custom elements in Angular allow developers to create reusable, encapsulated pieces of functionality tailored to their specific application needs.

Some examples of custom elements in Angular include:

  • Custom components: Reusable UI elements with their own template, style, and logic.
  • Custom directives: Extend HTML element behavior or appearance.
  • Custom pipes: Transform data for display.
  • Custom services: Provide shared functionality across components.

By creating custom elements, Angular developers can build more modular, maintainable, and feature-rich applications customized to specific project requirements.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved