0
0
Angularframework~5 mins

ngClass for dynamic classes in Angular - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is ngClass used for in Angular?

ngClass is a directive in Angular that lets you add or remove CSS classes dynamically based on component data or expressions.

Click to reveal answer
intermediate
How do you apply multiple classes conditionally using ngClass?
<p>You can pass an object to <code>ngClass</code> where keys are class names and values are conditions. Classes with true conditions get applied.</p><pre><code>&lt;div [ngClass]="{ 'class1': isActive, 'class2': hasError }"&gt;&lt;/div&gt;</code></pre>
Click to reveal answer
beginner
Can ngClass accept an array? How does it work?
<p>Yes. You can pass an array of class names to <code>ngClass</code>. All classes in the array will be added to the element.</p><pre><code>&lt;div [ngClass]="['class1', 'class2']"&gt;&lt;/div&gt;</code></pre>
Click to reveal answer
intermediate
What happens if the condition in ngClass changes at runtime?

Angular automatically updates the classes on the element to reflect the new condition. Classes are added or removed without page reload.

Click to reveal answer
beginner
Show a simple example of <code>ngClass</code> toggling a class based on a boolean variable <code>isActive</code>.
<button (click)="isActive = !isActive">Toggle</button>
<div [ngClass]="{ 'active-class': isActive }">Content</div>

Clicking the button adds or removes active-class on the div.

Click to reveal answer
What type of value can ngClass NOT accept?
AString with space-separated class names
BNumber representing class count
CObject with class names as keys and booleans as values
DArray of class names
How does Angular update classes when the condition in ngClass changes?
AIgnores changes after initial render
BManually requires developer to update classes
CReloads the whole page
DAutomatically adds or removes classes based on new conditions
Which syntax correctly applies multiple classes conditionally with ngClass?
AAll of the above
B[ngClass]="['class1', 'class2']"
C[ngClass]="'class1 class2'"
D[ngClass]="{ 'class1': true, 'class2': false }"
What is the benefit of using ngClass over static class attributes?
AAllows dynamic styling based on component state
BMakes HTML code longer
CPrevents CSS from loading
DDisables user interaction
If you want to add a class only when a variable hasError is true, which is correct?
A[ngClass]="['error', hasError]"
B[ngClass]="{ hasError: 'error' }"
C[ngClass]="{ 'error': hasError }"
D[ngClass]="hasError ? 'error' : ''"
Explain how ngClass helps in applying CSS classes dynamically in Angular components.
Think about how classes change when variables change in your component.
You got /4 concepts.
    Describe three different ways to use ngClass to add classes to an element.
    Consider the types of values you can bind to <code>ngClass</code>.
    You got /3 concepts.