ngClass helps you add or remove CSS classes on HTML elements easily based on conditions. It makes your page look different depending on your data or user actions.
ngClass for dynamic classes in Angular
<element [ngClass]="expression"></element>The expression can be a string, array, or object.
Use object syntax to add classes conditionally with true/false values.
<div [ngClass]="'active'">Content</div><div [ngClass]="['class1', 'class2']">Content</div><div [ngClass]="{ 'highlight': isActive, 'error': hasError }">Content</div>This component has a button that changes its background color when clicked by toggling the 'active' and 'inactive' classes. Another paragraph shows an error style when the 'hasError' flag is true. The second button toggles this error style.
import { Component } from '@angular/core'; @Component({ selector: 'app-dynamic-class', template: ` <button (click)="toggleActive()" [ngClass]="{ active: isActive, inactive: !isActive }"> Click me </button> <p [ngClass]="{ error: hasError }">This is a message.</p> <button (click)="toggleError()">Toggle Error</button> `, styles: [ `.active { background-color: lightgreen; }`, `.inactive { background-color: lightgray; }`, `.error { color: red; font-weight: bold; }` ] }) export class DynamicClassComponent { isActive = false; hasError = false; toggleActive() { this.isActive = !this.isActive; } toggleError() { this.hasError = !this.hasError; } }
ngClass updates classes automatically when the bound expression changes.
Use meaningful class names and keep styles in CSS for better separation.
Remember to import CommonModule in your Angular module to use ngClass.
ngClass lets you add or remove CSS classes dynamically in Angular templates.
You can use string, array, or object syntax to control classes.
It helps make your UI respond visually to data or user actions easily.
Practice
ngClass in Angular?Solution
Step 1: Understand what
ngClassdoesngClassis used to control CSS classes dynamically in Angular templates.Step 2: Compare options with
Only To add or remove CSS classes dynamically based on component data describes adding or removing CSS classes dynamically, which matchesngClasspurposengClassfunctionality.Final Answer:
To add or remove CSS classes dynamically based on component data -> Option AQuick Check:
ngClass controls CSS classes dynamically = A [OK]
- Confusing ngClass with event handling
- Thinking ngClass fetches data
- Mixing ngClass with component creation
ngClass with an array?Solution
Step 1: Identify array syntax for ngClass
Using an array, classes are listed inside square brackets and quotes: ['class1', 'class2'].Step 2: Check each option's syntax
<div [ngClass]="['class1', 'class2']"></div>correctly uses [ngClass] with an array.<div ngClass="class1 class2"></div>is plain string without binding.<div [ngClass]="{'class1': true, 'class2': false}"></div>uses object syntax, not array.<div [ngClass]="class1, class2"></div>is invalid syntax.Final Answer:
<div [ngClass]="['class1', 'class2']"></div> -> Option BQuick Check:
Array syntax = ['class1', 'class2'] [OK]
- Using string without binding for multiple classes
- Confusing object and array syntax
- Incorrect comma usage outside array
isActive = true;
classes = { 'active': isActive, 'disabled': !isActive };What classes will be applied in the template?
<div [ngClass]="classes">Content</div>Solution
Step 1: Evaluate the classes object values
isActive is true, so 'active': true, and 'disabled': !true = false.Step 2: Determine which classes are applied
Only keys with true values are applied. So only 'active' class is added.Final Answer:
The div will have class 'active' only -> Option CQuick Check:
True keys apply classes = A [OK]
- Assuming false keys add classes
- Confusing boolean values with strings
- Thinking all keys apply regardless of value
<div [ngClass]="{active: isActive, disabled: !isActive}">Test</div>Assuming
isActive is a boolean property in the component.Solution
Step 1: Check object syntax in ngClass binding
Angular allows unquoted property names in object literals inside templates.Step 2: Verify boolean usage and binding syntax
Boolean values are valid to conditionally apply classes. Square brackets are required for binding.Final Answer:
The syntax is correct; no error -> Option DQuick Check:
Object syntax with booleans is valid = B [OK]
- Thinking object keys must be quoted strings
- Removing square brackets breaks binding
- Believing booleans are invalid in ngClass
score is above 80 and 'low-score' when it is below or equal to 80. Which ngClass binding correctly implements this logic?Solution
Step 1: Analyze the condition for each class
'highlight' applies if score > 80, 'low-score' applies if score <= 80.Step 2: Check each option's logic
<div [ngClass]="{highlight: score > 80, 'low-score': score <= 80}"></div>correctly maps conditions to classes in an object.<div ngClass="score > 80 ? 'highlight' : 'low-score'"></div>lacks property binding [ngClass], so the ternary is not evaluated (static string).<div [ngClass]="['highlight', 'low-score']"></div>applies both classes always.<div [ngClass]="{highlight: score <= 80, 'low-score': score > 80}"></div>reverses conditions incorrectly.Final Answer:
<div [ngClass]="{highlight: score > 80, 'low-score': score <= 80}"></div> -> Option AQuick Check:
Object with correct conditions = C [OK]
- Applying both classes always with array syntax
- Reversing condition logic
- Forgetting property binding [ngClass] for dynamic expressions
Ready to prove it?
Pass the test and this pattern moves unknown
