How to build custom directives in Angular

Angular's custom directives provide a powerful mechanism for editing the DOM and incorporating dynamic behavior to templates.

How to build custom directives in Angular Picture 1How to build custom directives in Angular Picture 1

One of Angular's main features is directives. Angular directives give you a way to add behavior to DOM elements. Angular provides a wide range of directives. You can also create custom directives in this powerful framework.

What is Directive?

Directives are custom code that Angular uses to modify the behavior or visuals of an HTML element. You can use directives to add event listeners, change the DOM, and show or hide elements.

Angular has two types of directives: structural and attribute. Structural directives change the structure of the DOM, while attribute directives change the appearance or behavior of a component. Directives are an efficient way to extend Angular components.

Benefits of using Directive in Angular

  1. Can be reused in many components, saving you time and effort.
  2. Directives can be extended to add new functionality, making components more powerful.
  3. The flexibility to edit a component's behavior or visuals in a variety of ways gives you a lot of flexibility when building your app.

 

Set up Angular application

Install Angular CLI by running the code in terminal:

npm install -g @angular/cli

After installing Angular CLI, create an Angular project by running the following command:

ng new custom-directives-app

Running the above command will create an Angular project named custom-directives-app .

Create a custom command

Now you have an Angular project and can start creating custom directives. Create a TypeScript file and define a class that contains the @Directive decorator element .

@Directive is a TypeScript decorator used to create custom directives. Now create a file highlight.directive.ts in the src/app directory. In this file, you will create a custom directive: highlight .

For example:

import { Directive } from "@angular/core"; @Directive({ selector: "[myHighlight]", }) export class HighlightDirective { constructor() {} }

The above code block imports the decorator Directive from the @angular/core module . Decorato r @Directive modifies the HighlightDirective class. It takes an object as argument using a selector attribute .

In this case, you set the selector attribute to [myHighlight] , which means you can apply this directive to templates by adding the myHighlight attribute to an element.

Here is an example of how to use directives in templates:

Some text

Add behavior to Directive

Now you have successfully created a directive. The next step is to add behavior to the directive so it can manipulate the DOM. You will need ElementRef from @angular/core to add behavior to a directive.

You would inject ElementRef into the directive's constructor. ElementRef is a wrapper around the root element inside a viewer.

Here's an example of how to add behavior to a directive:

import { Directive, ElementRef } from "@angular/core"; @Directive({ selector: "[myHighlight]" }) export class HighlightDirective { constructor(private element: ElementRef) { this.element.nativeElement.style.backgroundColor = 'lightblue'; } }

 

In this example, the HighlightDirective class constructor takes the ElementRef parameter , which Angular automatically injects. ElementRef provides access to the underlying DOM element.

Using the this.element.nativeElement property , you have access to the root DOM element of the element parameter . Then you set the element's background color to lightblue using the style attribute . This means any element you apply to the myHighlight directive will have a light blue background.

To make the directive work, make sure you import and declare it in the app.module.ts file .

For example:

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HighlightDirective } from './highlight.directive'; @NgModule({ declarations: [ AppComponent, HighlightDirective, ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

You can now apply the myHighlight directive to elements in Angular components.

Some text

Run the application on the component server to test whether the directive works or not. You can do this by running the following command in terminal:

ng serve

After running this command, navigate to http://localhost:4200/ in your web browser, and you will see an interface that looks like the image below.

How to build custom directives in Angular Picture 2How to build custom directives in Angular Picture 2

Angular's built-in directives accept values ​​that change element images, but the myHighlight custom directive does not. You can configure the directive to accept a value that will be used to dynamically set the background color of the template.

To do this, replace the code in the highlight.directive.ts file with:

import { Directive, ElementRef, Input } from "@angular/core"; @Directive({ selector: "[myHighlight]" }) export class HighlightDirective { @Input() set myHighlight(color: string) { this.element.nativeElement.style.backgroundColor = color; } constructor(private element: ElementRef) { } }

In the above code block, the HighlightDirective class contains a setter method named myHightlight . It takes the color parameter of the type string. You modify the setter with decorator@Input , which allows you to pass color values ​​into the directive from the parent component.

 

Now you can decide the background color by passing the value to the myHighlight directive.

For example:

Some text

Create custom structural directives

Angular provides two structural directives: ngFor and ngIf . Directive ngFor displays a template for each item in the collection (array), while nglf handles rendering according to conditions.

In this section, you will create a custom structural directive that functions like the nglf directive. To do this, create a condition.directive.ts file .

In the condition.directive.ts file , write the following code:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core' @Directive({ selector: "[condition]" }) export class ConditionDirective { @Input() set condition(arg: boolean) { if(arg) { this.viewContainer.createEmbeddedView(this.template) } else { this.viewContainer.clear(); } } constructor( private template: TemplateRef, private viewContainer: ViewContainerRef ) {} }

This block of code allows you to conditionally display components by applying a conditional directive to a component and passing a boolean value from the parent component.

In the ConditionDirective class constructor , you insert an instance of TemplateRef and ViewContainerRef . TemplateRef represents the template associated with that directive, and ViewContainerRef represents the container in which the application displays view windows.

The ConditionDirective class setter method uses an if else statement to test the arg parameter. Directive creates an embedded window using the provided template if that parameter is true. The createEmbeddedView method of the ViewContainerRef class creates and displays the view in the DOM.

If that parameter is false , this directive will clear the view container using the clear method of the ViewContainerRef class . This removes any previously displayed viewers from the DOM.

After creating the directive, register it in the project by importing and declaring it in the app.module.ts file . After doing this, you can start using directives in your templates.

Here's an example of how to use it in your template:

Hello There!!!

Now you can freely create custom directives . Don't be afraid to use this function because it can help you edit the DOM and make the template more interesting.

4.5 ★ | 2 Vote