What are directives and what types exist in Angular?
What are Directives in Angular?
Directives are special classes in Angular that extend HTML element behavior. They allow changing DOM structure, adding styles or dynamically managing component logic.
Directive Types in Angular
Angular divides directives into three main categories:
| Type | Purpose | Examples |
|---|---|---|
| Attribute | Change element appearance or behavior | ngClass, ngStyle, customHighlight |
| Structural | Change DOM structure (add/remove elements) | ngIf, ngFor, ngSwitch |
| Custom | Directives you create for adding reusable logic | appTooltip, appValidate |
Attribute Directives
Applied to element as attributes. They can change:
- element style (
ngStyle) - class (
ngClass) - behavior through event listeners
Example: ngClass
html
<div [ngClass]="{ active: isActive }">Text</div>Custom Attribute Directive Example
typescript
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}html
<p appHighlight>Highlighted text</p>Structural Directives
Change DOM structure: add/remove elements.
Examples
html
<div *ngIf="isVisible">Show</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>*ngIf— conditional rendering.*ngFor— array iteration.*ngSwitch— multiple branching.
Creating Custom Directive
typescript
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appZoom]'
})
export class ZoomDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onEnter() {
this.el.nativeElement.style.transform = 'scale(1.1)';
}
@HostListener('mouseleave') onLeave() {
this.el.nativeElement.style.transform = 'scale(1)';
}
}html
<img src="..." appZoom />Difference from Components
| Characteristic | Directive | Component |
|---|---|---|
| Selector | [appDirective] (attribute) | <app-component> (tag) |
| Template | No | Yes |
| Usage | As behavior or style | As UI element |
| Tip: |
Use directives for reusable behavior that doesn't require template. If UI is needed — better create component.
Content
What are Directives in Angular?Directive Types in AngularAttribute DirectivesExample: ngClassCustom Attribute Directive ExampleStructural DirectivesExamplesCreating Custom DirectiveDifference from Components
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.