Directives in Angular

What Are Directives in Angular?

In Angular, directives are a crucial part of the framework that allows you to extend the functionality of HTML elements and attributes. They provide a way to create reusable components, apply behaviors to elements, and manipulate the DOM (Document Object Model) based on certain conditions. Angular directives are categorized into three main types: structural directives, attribute directives, and component directives.

  1. Structural Directives: Structural directives manipulate the structure of the DOM by adding or removing elements based on certain conditions. They are identified by the * prefix in their names. Some commonly used structural directives are:
    • ngIf: Adds or removes elements based on a given condition. If the condition evaluates to true, the element is included; otherwise, it’s removed.
    • ngFor: Iterates over a collection (array or object) and generates elements for each item in the collection.
    • ngSwitch: Switches among alternative views based on a provided expression’s value.

Example of ngIf:

<div *ngIf="isLogged">Welcome, User!</div>

Example of ngFor:

<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
  1. Attribute Directives: Attribute directives modify the appearance or behavior of elements by changing their attributes. They are used as attributes of HTML elements. Some common attribute directives include:
    • ngStyle: Dynamically sets CSS styles for an element based on specified conditions.
    • ngClass: Dynamically adds or removes CSS classes to/from an element based on specified conditions.

Example of ngStyle:

<div [ngStyle]="{ 'color': textColor, 'font-size': fontSize }">Styled Text</div>

Example of ngClass:

<div [ngClass]="{ 'active': isActive, 'highlighted': isHighlighted }">Dynamic Class</div>
  1. Component Directives: Component directives are user-defined components that encapsulate a specific piece of functionality and can be reused throughout an application. They are created using Angular’s component architecture and can be thought of as a more advanced form of directive.

Angular also allows you to create your own custom directives using the @Directive decorator. Custom directives are used to encapsulate and reuse behavior not covered by built-in directives.

Example of a Custom Directive:

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

@Directive({
selector: ‘[appCustomDirective]’
})
export class CustomDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = ‘yellow’;
}
}

<div appCustomDirective>This element has a custom directive applied.</div>

Directives are a powerful feature in Angular that enable you to create dynamic, interactive, and reusable components in your application. By using built-in directives and creating custom ones, you can enhance the user experience and streamline your codebase.