Search⌘ K
AI Features

Creating custom directives

Explore the process of creating custom attribute directives in Angular, including directive creation, service injection, and registration. Understand how to use HostListener and HostBinding to manage events and properties on host elements, enabling more dynamic Angular apps.

You might have used *ngIf, *ngFor by now in your Angular applications. These are the built-in directives that are provided to us by the Angular team. We’ll see how to create our very own directives in Angular. Before we create one, we need to understand the different types of custom directives.

We have discussed the following in the directives section before.

  • Component directives
  • Structural directives
  • Attribute directives

Follow the steps below to create our own custom attribute directives in Angular.

Step 1. Creating a directive by decorating a class with the @Directive decorator.

OR use the CLI to create a directive in your application.

ng generate directive <directive-name>

The directive would look something like this: ...