Angular templates define the HTML structure of a component. Directives are special instructions that modify the DOM behavior or appearance in your templates.
Directives are of two main types: Structural Directives (change DOM structure) and Attribute Directives (change element appearance or behavior).
1. Structural Directives
Structural directives change the layout or structure of the DOM.
*1.1 ngIf
Used to conditionally show or hide elements.
<p *ngIf="isLoggedIn">Welcome, user!</p>
<p *ngIf="!isLoggedIn">Please login</p>
isLoggedIn = true;
*1.2 ngFor
Used to render lists dynamically.
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
items = ['Angular', 'React', 'Vue'];
*1.3 ngSwitch
Used to conditionally display one element from multiple options.
<div [ngSwitch]="color">
<p *ngSwitchCase="'red'">Red selected</p>
<p *ngSwitchCase="'blue'">Blue selected</p>
<p *ngSwitchDefault>Other color</p>
</div>
color = 'blue';
2. Attribute Directives
Attribute directives change the appearance or behavior of elements without changing the DOM structure.
2.1 ngClass
Adds or removes CSS classes dynamically.
<p [ngClass]="{'active': isActive, 'inactive': !isActive}">Status</p>
isActive = true;
2.2 ngStyle
Dynamically sets inline CSS styles.
<p [ngStyle]="{'color': textColor, 'font-size.px': fontSize}">Styled Text</p>
textColor = 'red';
fontSize = 18;
2.3 Custom Directives
You can create your own directives to add custom behavior.
Example: HighlightDirective
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}
Usage in template:
<p appHighlight>Hover to highlight me!</p>
Summary
- Templates define the UI structure of a component.
- Structural Directives (
*ngIf,*ngFor,*ngSwitch) manipulate DOM elements. - Attribute Directives (
ngClass,ngStyle) change the appearance of elements. - Custom directives allow you to implement reusable behavior across your application.