Directives are special markers (like attributes) in HTML that tell Angular how to modify elements.
1️⃣ Component Directives – Used to create reusable UI components.
2️⃣ Structural Directives – Modify the DOM structure (*ngIf
, *ngFor
).
3️⃣ Attribute Directives – Change the behavior or appearance of elements (ngClass
, ngStyle
).
A Component Directive is simply an Angular component. It consists of:
✅ Selector (defines how to use it in HTML)
✅ Template (HTML content)
✅ Styles (CSS for the component)
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `<h2>Welcome to Angular Directives</h2>`,
styles: [`h2 { color: blue; }`]
})
export class ExampleComponent { }
Usage in HTML:
<app-example></app-example>
Structural directives modify the DOM structure dynamically.
*ngIf
*ngIf
removes or adds an element based on a condition.
<p *ngIf="isLoggedIn">Welcome, User!</p>
isLoggedIn = true; // The paragraph will be displayed
*ngFor
*ngFor
loops through a list and displays items.
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
items = ['Angular', 'React', 'Vue'];
*ngSwitch
*ngSwitch
is used for multiple conditional cases.
<div [ngSwitch]="status">
<p *ngSwitchCase="'active'">User is active</p>
<p *ngSwitchCase="'inactive'">User is inactive</p>
<p *ngSwitchDefault>Unknown status</p>
</div>
status = 'active';
Attribute directives modify the behavior or styling of an element.
ngClass
Dynamically apply CSS classes.
<p [ngClass]="{'text-success': isActive, 'text-danger': !isActive}">Status Message</p>
ngStyle
Dynamically apply styles.
<p [ngStyle]="{'color': isActive ? 'green' : 'red'}">Dynamic Text</p>
You can create a custom directive using Angular CLI:
ng generate directive highlight
Modify highlight.directive.ts
:
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
}
}
Usage in HTML
<p appHighlight>Hover over this text to see the effect!</p>
✔️ Angular Directives enhance HTML elements and enable dynamic behavior.
✔️ Structural Directives modify the DOM (*ngIf
, *ngFor
, *ngSwitch
).
✔️ Attribute Directives change styling (ngClass
, ngStyle
).
✔️ Custom Directives allow for reusable functionalities.
Mastering Angular Directives improves the development of dynamic and interactive applications! 🚀