Steps to create the Directive
Step 1: Create the angular project using the following command.
ng new custom-directive
cd custom-directive
Step 2: To generate a new directive, we can use the following command.
ng generate directive sampleColorChange
Folder Structure:
Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/platform-server": "^17.3.0",
"@angular/router": "^17.3.0",
"@angular/ssr": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.0",
"@angular/cli": "^17.3.0",
"@angular/compiler-cli": "^17.3.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
Example: Implementing the directive
<!-- app.component.html -->
<div appSampleColorChange>Text using directive</div>
//sample-color-change.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appSampleColorChange]',
})
export class SampleColorChangeDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.color = 'blue';
this.el.nativeElement.style.fontWeight = 'bold';
}
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = 'red';
}
}
To start the application run the following command.
ng serve
Output:
Here, in the above example we have a custom directive which changes colour of the text to blue initially, on on mouse hover it changes the background colour to red. We have used HostListener to detect mouse events and perform required operations.We can also pass multiple inputs to our directives . Using @Input() decorator we can access them in the directive class and perform the necessary changes.
Purpose of the @Directive decorator.
In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior. The `@Directive` decorator in Angular is used to create a directive, which is a class that allows us to attach behavior to elements in the DOM. Directives are a way to extend the functionality of HTML elements and attributes in Angular applications.
Contact Us