0
0
Angularframework~20 mins

ngClass for dynamic classes in Angular - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
ngClass Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
How does ngClass apply classes dynamically?
Given this Angular template snippet, what classes will be applied to the
when isActive is true and hasError is false?

<div [ngClass]="{ 'active': isActive, 'error': hasError }">Content</div>
AThe div will have no classes applied.
BThe div will have the class 'error' only.
CThe div will have the class 'active' only.
DThe div will have both 'active' and 'error' classes.
Attempts:
2 left
💡 Hint
Remember ngClass adds classes where the condition is true.
📝 Syntax
intermediate
2:00remaining
Identify the correct ngClass syntax for multiple classes
Which option correctly applies multiple classes 'btn' and 'btn-primary' using ngClass in Angular?
A[ngClass]="{'btn': true, 'btn-primary': true}"
B[ngClass]="{'btn btn-primary': true}"
C[ngClass]="['btn', 'btn-primary']"
D[ngClass]="('btn', 'btn-primary')"
Attempts:
2 left
💡 Hint
ngClass accepts arrays or objects with boolean values.
🔧 Debug
advanced
2:00remaining
Why does this ngClass binding not apply the class?
Consider this Angular template:
<div [ngClass]="{ active: isActive }">Hello</div>

and component code:
isActive = '';

Why does the 'active' class not get applied?
ABecause ngClass only accepts arrays, not objects.
BBecause isActive is a string '', not a boolean true.
CBecause the class name 'active' must be in quotes.
DBecause the div element cannot have dynamic classes.
Attempts:
2 left
💡 Hint
Check the type of the condition value.
state_output
advanced
2:00remaining
What classes are applied after toggling state?
Given this component code:
isError = false;
toggle() { this.isError = !this.isError; }

and template:
<button (click)="toggle()">Toggle</button>
<div [ngClass]="{ 'error': isError, 'normal': !isError }">Status</div>

What classes does the div have after clicking the button twice?
AThe div has class 'error'.
BThe div has no classes.
CThe div has both 'error' and 'normal' classes.
DThe div has class 'normal'.
Attempts:
2 left
💡 Hint
Each click toggles isError between true and false.
🧠 Conceptual
expert
2:00remaining
How does ngClass handle null or undefined values in class bindings?
If you use ngClass with an object like { 'highlight': isHighlighted, 'disabled': isDisabled } and isHighlighted is null and isDisabled is undefined, what classes will Angular apply?
ANo classes will be applied because null and undefined are treated as false.
BBoth 'highlight' and 'disabled' classes will be applied.
COnly 'highlight' class will be applied because null is truthy.
DOnly 'disabled' class will be applied because undefined is truthy.
Attempts:
2 left
💡 Hint
Think about how JavaScript treats null and undefined in boolean contexts.