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

<!-- If isUrgent is true, the 'urgent' class is added. If isError is true, the 'error' class is added. --> <div [ngClass]="{ 'urgent': isUrgent, 'error': isError, 'active': true }"> Status Message </div>

Syntax 2: Array of Class Names

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

html

<div [ngClass]="classList">Multiple Classes</div>

2. NgStyle

NgStyle dynamically sets inline styles for an HTML element.

typescript currentSize: number = 24;

html

<!-- Setting multiple inline styles based on component properties --> <p [ngStyle]="{ 'font-size.px': currentSize, 'color': isUrgent ? 'red' : 'green' }"> Styled Text </p>

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