Open In App

Purpose of the @Directive decorator.

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Prerequisites:

What is Directives?

The @Directive decorator is a TypeScript decorator provided by Angular that is used to create custom directives. Directives in Angular are classes decorated with @Directive that defined behavior and logic to be applied to HTML elements in the DOM. These directives can manipulate the appearance, behavior, or structure of elements based on certain conditions or user interactions.

Syntax:

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

@Directive({
selector: '[appBasicDirective]',
})
export class BasicDirective {
constructor() {}
}

Features of Directives

  • Reusability: Directives combine specific functionalities that allows you to reuse them across different parts of the application. This promotes code maintainability and reduces duplication.
  • Attribute Modification: Attribute directives can dynamically add, remove, or modify attributes of HTML elements based on data or expressions. This allows for flexible styling and behavior control.
  • Template Manipulation: Structural directives like *ngIf and *ngFor manipulate the template itself, that allows to conditionally display or iterate over elements based on data.
  • Encapsulation: Directives encapsulate logic and behaviour within a class, that provides separation of concerns and making our code more maintainable.
  • Access to Host Elements : Directives have access to host elements they are applied to, allowing them to interact with the element and its properties.

Types of Directives

There are two main categories of directives, each serving different purposes:

1. Structural Directives

In Angular, structural directives are a type of directive that modify the layout of the DOM by adding, removing, or replacing elements based on certain conditions. These directives include ngIf, ngFor and ngSwitch. Let’s explore each of these directives in detail.

  1. *ngIf Directive: This directive helps us to conditionally include or remove elements from the DOM. Using ngIf directive we can create dynamic user interfaces.
  2. *ngFor Directive: This directive helps us to iterate overIterates over a collection of data and creates a DOM element for each item. This is similar to for loop in our programming languages.
  3. *ngSwitch Directive: This directive helps us to conditionally display an element from different section of elements based on given expression. It is similar to switch case in our programming languages.

2. Attribute Directives

These attributes are used within html tags to modify the appearance of elements, components or directives. These are applied to elements as attributes and can take inputs and react to changes in that input data.These directives include ngClass, ngStyle and ngMode. Let’s explore each of these directives in detail.

  1. ngClass: This attribute is used to conditionally give the classes to the elements based on the value binded to ngClass directive.
  2. ngStyle: This attribute is used to dynamically apply the styles to elements based on the value binded to ngStyle directive. It helps us to modify the appearance of elements on conditional basis.
  3. ngModel: This attribute is generally used to bind form control data to a class variable . This allows a two way binding and this is most commonly used directive with forms. It also comes with few basic validations like required,minLength , maxLength which can be directly used in our input tags.

A custom directive in Angular is a user-defined directive that extends the functionality of HTML by introducing new behaviors or attributes. Unlike built-in directives provided by Angular, custom directives are created to encapsulate specific functionality and promote code reuse within Angular applications.

Purpose of Directives

  • Directives in Angular extend HTML’s capabilities and allow us to manipulate the DOM.
  • Directives help us to create reusable components and enhance code re usability.
  • Customising element behaviour is possible using Angular directives.
  • Directives enhance the re usability of code by encapsulating functionality.
  • Attribute directives modify element behaviour, while structural directives alter the DOM’s structure.

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:

Screenshot-2024-03-12-185510

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

HTML
<!-- app.component.html -->
<div appSampleColorChange>Text using directive</div>
JavaScript
//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:


output_pLttcu

Purpose of the @Directive decorator


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads