Skip to main content

Common Directives

Angular’s @angular/common package provides essential directives for manipulating the DOM structure and styling elements in your templates.
Deprecation Notice: Structural directives (ngIf, ngFor, ngSwitch) are deprecated as of Angular v20 and will be removed in v22. Use the new control flow syntax instead.

Structural Directives

Structural directives change the DOM structure by adding or removing elements.

NgIf

Conditionally includes a template based on the value of an expression.
Import:
Source: packages/common/src/directives/ng_if.ts:166

NgFor

Renders a template for each item in a collection.
Import:
Source: packages/common/src/directives/ng_for_of.ts:177
Always provide a trackBy function for better performance when iterating over large lists or lists that change frequently.

NgSwitch

Switches between views based on a matching expression.
Import:
Source: packages/common/src/directives/ng_switch.ts:120
As of Angular v17, NgSwitch uses strict equality (===) instead of loose equality (==) for matching cases.

Attribute Directives

Attribute directives modify the appearance or behavior of DOM elements without changing the structure.

NgClass

Adds and removes CSS classes on an HTML element.
Import:
Source: packages/common/src/directives/ng_class.ts:79
For simple use cases, prefer class bindings like [class.active]="isActive" instead of ngClass.

NgStyle

Updates styles for the containing HTML element.
Import:
Source: packages/common/src/directives/ng_style.ts:64
For simple use cases, prefer style bindings like [style.color]="color" instead of ngStyle.

Usage Notes

Importing Directives

Performance Considerations

Always use trackBy with *ngFor when rendering lists that may change:
  • NgClass and NgStyle implement custom change detection for deep object comparison
  • Use immutable data patterns for better performance
  • Consider using direct bindings for simple cases

See Also

Control Flow

Modern control flow syntax

Template Syntax

Angular template guide

Structural Directives

Creating custom directives

Pipes

Common pipes reference