Bird
0
0

Consider this Angular template:

medium📝 Debug Q14 of 15
Angular - Directives
Consider this Angular template:
<div *ngIf="user.isLoggedIn">Hello, {{user.name}}!</div>

But the app crashes with an error: Cannot read property 'isLoggedIn' of undefined. What is the best fix?
ARemove the *ngIf directive completely.
BChange to <code>*ngIf="user?.isLoggedIn"</code> to safely check property.
CInitialize <code>user</code> as an empty object in the component.
DUse <code>*ngIf="user.isLoggedIn === true"</code> instead.
Step-by-Step Solution
Solution:
  1. Step 1: Identify cause of error

    The error occurs because user is undefined when Angular tries to read user.isLoggedIn.
  2. Step 2: Use safe navigation operator

    Using user?.isLoggedIn prevents error by checking if user exists before accessing isLoggedIn.
  3. Final Answer:

    Change to *ngIf="user?.isLoggedIn" to safely check property. -> Option B
  4. Quick Check:

    Use ? to avoid errors on undefined objects [OK]
Quick Trick: Use ?. to safely access nested properties [OK]
Common Mistakes:
  • Removing *ngIf loses conditional rendering
  • Initializing user empty but not fixing undefined timing
  • Checking equality without safe navigation still errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes