Skip to main content
Practice Problems

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:

TypePurposeExamples
AttributeChange element appearance or behaviorngClass, ngStyle, customHighlight
StructuralChange DOM structure (add/remove elements)ngIf, ngFor, ngSwitch
CustomDirectives you create for adding reusable logicappTooltip, 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

CharacteristicDirectiveComponent
Selector[appDirective] (attribute)<app-component> (tag)
TemplateNoYes
UsageAs behavior or styleAs 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems