Angular directives are powerful tools that allow you to manipulate the DOM and extend HTML capabilities. There are three main types of directives in Angular:
- Component Directives
- Structural Directives
- Attribute Directives
1. Component Directives
Component directives are the most common type, and they are actually the Angular components you create. Each component directive is associated with a template, which defines a view.
- Example:typescriptCopy code
@Component({ selector: 'app-example', template: `<h1>{{title}}</h1>`, styles: [`h1 { font-weight: normal; }`] }) export class ExampleComponent { title = 'Hello Angular'; }
2. Structural Directives
Structural directives alter the DOM layout by adding or removing elements. They can change the structure of the DOM.
- Common Structural Directives:
*ngIf: Conditionally includes a template based on the value of an expression.*ngFor: Iterates over a collection, creating a template instance for each item.*ngSwitch: A set of directives that switch between alternative views.
- Examples:
*ngIf:htmlCopy code<div *ngIf="isVisible">This div is visible if isVisible is true.</div>*ngFor:htmlCopy code<ul> <li *ngFor="let item of items">{{item}}</li> </ul>*ngSwitch:htmlCopy code<div [ngSwitch]="value"> <div *ngSwitchCase="'A'">Value is A</div> <div *ngSwitchCase="'B'">Value is B</div> <div *ngSwitchDefault>Value is neither A nor B</div> </div>
3. Attribute Directives
Attribute directives change the appearance or behavior of an element, component, or another directive. Unlike structural directives, they do not change the DOM layout.
- Common Attribute Directives:
ngClass: Adds and removes a set of CSS classes.ngStyle: Adds and removes a set of HTML styles.ngModel: Binds an input, select, textarea, or custom form control to a model.
- Examples:
ngClass:htmlCopy code<div [ngClass]="{'class1': condition1, 'class2': condition2}">Styled div</div>ngStyle:htmlCopy code<div [ngStyle]="{'font-size': fontSize, 'color': fontColor}">Styled div</div>ngModel:htmlCopy code<input [(ngModel)]="userName"> <p>Hello {{userName}}!</p>
Creating Custom Directives
You can create custom attribute directives to encapsulate common behaviors or functionality.
- Steps to Create a Custom Directive:
- Generate Directive: Use Angular CLI to generate a directive.shCopy code
ng generate directive appHighlight - Implement Directive: Add the directive logic in the generated file (
app-highlight.directive.ts).typescriptCopy codeimport { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { @Input() appHighlight: string; constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.highlight(this.appHighlight || 'yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } } - Use Directive in Template: Apply the custom directive to an element.htmlCopy code
<p appHighlight="lightblue">Highlight me on hover!</p>
- Generate Directive: Use Angular CLI to generate a directive.shCopy code
Built-in Directives
Angular provides several built-in directives for common tasks. Some of them include:
- NgClass: Adds or removes CSS classes.
- NgStyle: Adds or removes inline styles.
- NgModel: Binds form controls to model properties.
- NgIf: Conditionally includes or excludes an element in the DOM.
- NgFor: Iterates over a list and renders an element for each item.
- NgSwitch: Conditionally switches between alternative views.
Summary
Directives are a fundamental part of Angular, allowing you to create dynamic, interactive, and reusable UI components. By leveraging the power of built-in and custom directives, you can greatly enhance the functionality and user experience of your Angular applications.
