In Angular, directives are powerful tools that allow you to extend the HTML syntax, providing additional behavior to elements or manipulating the DOM (Document Object Model). They enable you to create reusable components, attach behavior to elements, and transform the DOM structure.
Angular has three types of directives:
-
Component Directives:
- Components are a type of directive with a template. They encapsulate both the UI (HTML) and the logic (JavaScript/TypeScript) into a reusable and self-contained unit.
- A component directive consists of a TypeScript class (component class) and an HTML template.
-
Attribute Directives:
- Attribute directives change the appearance or behavior of an element, component, or another directive. They are applied as attributes in HTML elements.
-
Examples include
ngStyle, ngClass
and custom attribute directives like ones you define for specific functionalities.
-
Structural Directives:
- Structural directives modify the DOM layout by adding, removing, or manipulating elements.
- They use the HTML structure to conditionally display elements based on certain conditions.
-
Examples include
*ngIf, *ngFor
, and custom structural directives that alter the layout or structure of the DOM based on specified rules.
How Directives Work:
- Directives are markers on DOM elements that tell Angular to attach specific behavior to those elements or transform them.
- They are used within templates to make the application more dynamic and interactive.
Custom Directives:
- Angular allows developers to create custom directives to extend the behavior of HTML elements.
- Custom directives can encapsulate complex behavior and be reused throughout the application.
Example:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string | null) {
this.el.nativeElement.style.backgroundColor = color;
}
}
In this example:
-
@Directive
vf decorator defines a custom directive namedappHighlight
. -
@HostListener
attaches event listeners to the host element (mouseenter and mouseleave
). -
ElementRef
gives access to the DOM element on which the directive is applied. - The directive changes the background color of the element when hovered.
Directives are essential in Angular for creating reusable components, enhancing HTML elements with additional functionalities, and manipulating the DOM dynamically based on application logic.