Angular-directives

Understanding Angular Directives

Angular Directives are one of the core features of Angular, allowing developers to extend HTML's capabilities and build dynamic, interactive applications. Directives help in modifying the DOM, applying behavior, and creating reusable UI components.

Angular Directives

Types of Angular Directives

There are three main types of directives in Angular:

1. Component Directives

Component directives are the most commonly used type of directives. They include a template, styles, and logic, making them the fundamental building blocks of an Angular application.

2. Structural Directives

Structural directives change the structure of the DOM by adding or removing elements. The most common structural directives include:

  • *ngIf: Conditionally adds or removes elements from the DOM.
  • *ngFor: Iterates over an array and creates elements dynamically.
  • *ngSwitch: Displays elements based on a switch-case condition.

3. Attribute Directives

Attribute directives change the behavior or appearance of an element. Some common attribute directives include:

  • ngClass: Dynamically applies CSS classes.
  • ngStyle: Dynamically changes styles based on conditions.
  • Custom attribute directives can be created to modify element behavior.

Creating a Custom Directive

Developers can create their own directives using Angular's @Directive decorator. Below is an example of a custom directive that highlights text when hovered over:

@Directive({
      selector: '[appHighlight]'
    })
    export class HighlightDirective {
      constructor(private el: ElementRef) {
        this.el.nativeElement.style.backgroundColor = 'yellow';
      }
    }

To use this directive, simply apply it to any element in an Angular template:

<p appHighlight>This text is highlighted!</p>