Back to course

Introduction to Built-in Attribute Directives (NgClass, NgStyle)

The Complete Angular Developer: From Zero to Hero

14. Built-in Attribute Directives (NgClass, NgStyle)

Angular directives are classes that add extra behavior to elements in the application. Attribute directives change the appearance or behavior of an element.

What is an Attribute Directive?

Attribute directives look and behave like standard HTML attributes (e.g., ngModel, NgClass). They are bound using property binding syntax [ ].

1. NgClass

NgClass dynamically adds or removes CSS classes based on the component's state or a boolean expression.

Syntax 1: Key-Value Object

Use an object where the key is the class name (string) and the value is a boolean expression.

typescript export class StatusComponent { isUrgent: boolean = true; isError: boolean = false; }

html

Status Message

Syntax 2: Array of Class Names

typescript classList: string[] = ['highlight', 'border-red'];

html

Multiple Classes

2. NgStyle

NgStyle dynamically sets inline styles for an HTML element.

typescript currentSize: number = 24;

html

Styled Text

Note: When setting pixel values, you can use 'font-size' (string) or 'font-size.px' (string with unit suffix).