NG.II · Angular 22 practice question

When dynamically applying styles or classes to an element based on the value of a signal in Angular, what is the recommended pattern to ensure reactivity and avoid unnecessary change detection cycles? Consider the following scenario where `isError` is a boolean signal:

// Component
isError = signal(false);

// Template usage
// Assume the goal is to apply 'text-danger' class when isError() is true.
Choose one answer
Check answer and explanation

Correct answer: Using `[class.text-danger]="isError()"` on the host element.

Explanation

When binding a class or style based on a signal's value, Angular template bindings automatically handle reading the signal's current value. For simple boolean toggles, binding directly to the signal reference (if the signal is accessible and its value is what's being checked, as in the comparison syntax) or using the signal's value directly in the expression is the most idiomatic and performant approach. Option D, `<div [class.text-danger]="isError"></div>` (if `isError` is exposed or treated like a getter), or more correctly, `<div [class.text-danger]="isError()"></div>` is the direct binding pattern. However, since the question asks for the *recommended pattern* that handles reactivity efficiently, using the standard property binding approach (`[class.className]="expression"`) where the expression evaluates the signal is correct. In the context of this specific anti-pattern question (avoiding overhead), direct attribute binding is preferred over complex `ngStyle` computations when simple class toggling suffices. Option D, assuming the template binding context handles signals correctly, represents the cleanest binding mechanism for a boolean state.

Common trap

Options A and C involve potentially unnecessary wrapper functions or complex `ngStyle` usage when a simple class binding (`[class.className]="signal()"`) suffices, which can sometimes be less optimized than the direct binding mechanism for simple toggles.

Source: Angular Guide Templates (https://angular.dev/guide/templates)
Checked against the cited text on 2026-11-27.

Report an error in this question