Bird
0
0

How can you bind a nested property, such as user.profile.pictureUrl, to an <img> tag's src attribute safely to avoid errors if profile is undefined?

hard📝 Application Q9 of 15
Angular - Templates and Data Binding
How can you bind a nested property, such as user.profile.pictureUrl, to an <img> tag's src attribute safely to avoid errors if profile is undefined?
A<img [src]="user?.profile?.pictureUrl">
B<img [src]="user.profile.pictureUrl">
C<img src="{{user.profile.pictureUrl}}">
D<img [src]="user.profile.pictureUrl || '/default.jpg'">
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe navigation operator usage

    The safe navigation operator ?. prevents errors if intermediate properties are undefined.
  2. Step 2: Compare options

    The safe navigation operator ?. in [src]="user?.profile?.pictureUrl" prevents errors if intermediate properties are undefined or null. Direct access like [src]="user.profile.pictureUrl", interpolation src="{{user.profile.pictureUrl}}", or logical OR [src]="user.profile.pictureUrl || '/default.jpg'" will throw errors because they try to access pictureUrl on undefined.
  3. Final Answer:

    <img [src]=\"user?.profile?.pictureUrl\"> -> Option A
  4. Quick Check:

    Use ?. to safely access nested properties [OK]
Quick Trick: Use ?. to safely bind nested properties [OK]
Common Mistakes:
  • Not using safe navigation causing runtime errors
  • Using interpolation without safe checks
  • Overcomplicating with long logical expressions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes