How to create custom directives in Angular 8?


In Angular, directives are one of the most important elements. Directives are building blocks like components in angular framework to build application. A directive used to modify the DOM by changing the appearance, behavior, or layout of DOM elements.

Directives are used to provide or generate new HTML based syntax which will extend the power of the UI in an Angular Application. Each and every directive must have a selector same like a component. In simple words, every component in angular is a directive with the custom HTML template.

In angular, we have directives to change the behavior or structure of the HTML DOM elements. Directives are divided into 3 categories.

  • Component directives

  • Structural directives like *ngIf, *ngFor, *ngSwitch

  • Attribute directives like *ngStyle, *ngClass

We can also create custom directives.

Let’s look into the example below.

Custom Directive

Creating a custom directive is like creating angular component. To create a custom directive, we need to replace @Component with @Directive decorator.

Creating attribute custom directive

Let’s take an example for highlight selected DOM by setting up some background color. Let’s create custom directive for it.

Example

First, create one directive file. Like, show-highlight.directive.ts file in src/app folder.

import { Directive, ElementRef } from "@angular/core"; @Directive({ selector: "[highlightEle]" }) export class ShowHighlightDirective { constructor(private elementRef: ElementRef) { this.elementRef.nativeElement.style.color = "green"; } }

Here, ElementRef helps us to accessing the DOM elements. The selector i.e. highlightEle we can this selector anywhere in our application. If have same highlighting functionality anywhere in our application, we can simply use this selector.

After creating directive, we need to import that one in app.module.ts file. Like,

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

Here, we imported service class as providers. In @NgModule, we have four sections.

Declarations - Define imported components and directives

Imports- Define imported modules

Providers- Define imported services

Bootstrap- Define root component to display data

Now, let’s use hightlightEle selector in our component.

In app.component.html file

<div> <p highlightEle>Custom Attribute directive</p> </div>

Output

Custom Attribute directive
You have successfully created custom directive

Custom Structural directive

We have structural directive *ngIf. Now, we are same functionality as a custom. Let’s look into below example

Create one directive as custom-if.diretive.ts in src/app.

Add code as given below in custom-if.directive.ts file. Like,

import { Directive, ViewContainerRef, TemplateRef, Input } from "@angular/core"; @Directive({ selector: "[customIf]" }) export class customIfDirective { customIf: boolean; constructor( private viewContainer: ViewContainerRef, private templateRef: TemplateRef<any> ) {} @Input() set customIf(condition) { this.customIf = condition; this.updateView(); } updateView() { if (this.customIf) { this.viewContainer.createEmbeddedView(this.templateRef); } else { this.viewContainer.clear(); } } }

Here, ViewContainerRef and TemplateRef instances, we used to manipulate the DOM. We created property binding with @Input decorator. Whenever condition changes by clicking checkbox, setter function will be called. If the condition is true it are adding data into HTML template using createEmbeddedView otherwise clearing the HTML element.

Now, let’s import directive into app.module.ts. Like,

import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { AppComponent } from "./app.component"; import { customIfDirective } from "./custom-if.directive"; @NgModule({ declarations: [AppComponent, customIfDirective], imports: [BrowserModule, FormsModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {}

We added directive above main module. Let’s use created directive selector in app.component.html file. Like,

<h1>Custom structural directive</h1> Show Me <input type="checkbox" [(ngModel)]="check" /> <div *customIf="check"> Using the custom directive </div> <div *ngIf="check"> Using the ngIf directive </div>

Define show value in app.component.ts file. Like

import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { check = false; }

Ouput

When we click on checkbox, output will show like

Like, this we can create our directive and we can use anywhere in our application.

We observed from the above, directives can be useful to implement any custom logic on DOM elements. Directives helps to us reusability of code. Angular providing some built-in directives also. We can our own directives based on requirement.

Updated on: 21-Feb-2023

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements