This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Angular Custom Directive


Custom Directive

Angular Directives are used to extend the capability of HTML elements. It is also useful to alter the existing HTML element behaviors or style. Here, we'll see some simple steps to create a custom directive.

Step 1: - Creating a Directive

To create a directive, the following CLI command use in visual studio code.

ng generate directive customdirective

The CLI above command creates src/app/customdirective.directive.ts, a corresponding test file src/app/customdirective.directive.spec.ts and declares the directive class in the application AppModule.

PS D:\AngularProgram\Customdirective> ng generate directive customdirective
CREATE src/app/customdirective.directive.spec.ts (260 bytes)
CREATE src/app/customdirective.directive.ts (159 bytes)
UPDATE src/app/app.module.ts (495 bytes)

Angular Custom file

The CLI generates the default src/app/customdirective.directive.ts as follows:

import { Directive } from '@angular/core';

@Directive({
selector: '[appCustomdirective]'
})
export class CustomdirectiveDirective {
constructor() { }
}

Step 2: - Directive Constructor

Import ElementRef from @angular/core give direct access to the host DOM element through its nativeElement property.

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

Now this step you need to add ElementRef in the directive constructor to add a reference to the DOM element, the element to which you apply appCustomdirective as following.

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

@Directive({
  selector: '[appCustomdirective]'
})
export class CustomdirectiveDirective {
  constructor(private el: ElementRef) {  
  }
}

Add logic to the CustomdirectiveDirective class that sets the background to red.

this.el.nativeElement.style.backgroundColor = 'red';

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

@Directive({
  selector: '[appCustomdirective]'
})
export class CustomdirectiveDirective {
  constructor(private el: ElementRef) {  
  this.el.nativeElement.style.backgroundColor = 'red';
  }
}
Step 3:- Applying an attribute directive

To use the Customdirective, add a <p> element to the HTML template with the directive as an attribute in src/app/app.component.html.

<h2>Custom Directive Example</h2>
<p appCustomdirective>Custom Directive!</p>
<router-outlet></router-outlet>

Now Run the application. Output looks like that:

Angular Custom Directive


Prev Next