What are directives in Angular ?

 In Angular, directives are one of the core building blocks used to extend HTML's capabilities by creating reusable components or altering the behavior of the DOM. Directives are special markers (usually attributes or elements) in the HTML code that Angular uses to add additional functionality or behavior to elements in the DOM (Document Object Model).

There are three main types of directives in Angular:

  1. Component Directives

    • A component is essentially a directive with a template. Technically, every Angular component is also a directive.
    • Components are used to define views and manage the user interface in Angular. They are usually the most common type of directive.
    • Example:
      typescript

      @Component({ selector: 'app-user-profile', template: '<h2>{{ user.name }}</h2>', }) export class UserProfileComponent { user = { name: 'John Doe' }; }
      In this example, UserProfileComponent is a directive with an associated template (<h2>{{ user.name }}</h2>).
  2. Structural Directives

    • Structural directives are responsible for changing the structure of the DOM by adding or removing elements. These directives modify the layout of the DOM by adding, removing, or manipulating elements based on conditions or loops.
    • Structural directives typically start with an asterisk (*) in the template.
    • Common examples of structural directives:
      • *ngIf: Conditionally includes an element in the DOM.
      • *ngFor: Loops through a list and creates a new element for each item.
      • *ngSwitch: Conditionally renders a set of elements based on a case or condition.

    Example of *ngIf:

    html

    <div *ngIf="isVisible">This content is conditionally visible.</div>

    If isVisible is true, the <div> will be added to the DOM; if it's false, the <div> will be removed.

    Example of *ngFor:

    html

    <ul> <li *ngFor="let item of items">{{ item }}</li> </ul>

    This directive repeats the <li> element for each item in the items array.

  3. Attribute Directives

    • Attribute directives are used to change the appearance or behavior of an existing element in the DOM. They don’t change the structure of the DOM but modify the element’s properties, styles, or add event listeners.
    • These directives are applied as attributes to an HTML element.
    • Examples of attribute directives include:
      • ngClass: Adds or removes CSS classes from an element.
      • ngStyle: Dynamically sets styles on an element.
      • ngModel: Binds the value of an input element to a property in the component.

    Example of ngClass:

    html
    <div [ngClass]="{ 'highlighted': isHighlighted }">This is a highlighted element.</div>

    If isHighlighted is true, the class highlighted will be added to the div, otherwise, it won’t be added.

    Example of ngStyle:

    html
    <div [ngStyle]="{ 'color': color }">This text changes color dynamically.</div>

    The color of the text will be dynamically bound to the color property in the component.

Key Points About Directives:

  • Directives are used to extend HTML functionality by adding behavior to DOM elements.
  • Components are a type of directive with templates, whereas other directives (structural and attribute) are used for modifying the DOM in different ways.
  • Custom directives can be created to implement specific logic or functionality that is reusable across the application.

How Directives Work:

  • Structural Directives (like *ngIf or *ngFor) are applied to elements and can either create or remove elements from the DOM based on the conditions they are given.
  • Attribute Directives (like ngClass, ngStyle) are applied to the properties or styles of DOM elements and can change their appearance or behavior dynamically.

Creating Custom Directives:

You can create custom directives in Angular to handle specific tasks that you need to reuse across your app. Here's a simple example of a custom attribute directive:

Example of a custom directive that changes the background color:

  1. Create the directive:

    typescript

    import { Directive, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appHighlight]' // This is how you apply the directive in your HTML }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) { this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow'); } }
  2. Use the directive in your template:

    html
    <div appHighlight>Highlighted Text</div>

In this example, the appHighlight directive changes the background color of the element it's applied to.

Conclusion:

Directives in Angular are a powerful way to extend HTML and add custom functionality or behavior to DOM elements. There are built-in directives for structural (e.g., *ngIf, *ngFor) and attribute (e.g., ngClass, ngStyle) manipulations, and you can create your own custom directives to encapsulate reusable functionality. This helps keep Angular applications modular, clean, and maintainable.

Comments

Popular posts from this blog

Is there a compatibility list for Angular / Angular-CLI and Node.js?

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

How to resolve CORS issue in Angular 12?