Bird
0
0

Which is the best way to use RouterLink in the template to handle this condition?

hard📝 state output Q15 of 15
Angular - Routing
You want to create a navigation link that goes to a user detail page with a dynamic user ID, but only if the ID is valid (non-null). Which is the best way to use RouterLink in the template to handle this condition?
A<a [routerLink]="userId ? ['/user', userId] : ['/user']">User Details</a>
B<a *ngIf="userId" [routerLink]="['/user', userId]">User Details</a>
C<a [routerLink]="['/user', userId || 'default']">User Details</a>
D<a [routerLink]="/user/{{userId}}">User Details</a>
Step-by-Step Solution
Solution:
  1. Step 1: Understand conditional RouterLink binding

    <a [routerLink]="userId ? ['/user', userId] : ['/user']">User Details</a> uses a ternary operator inside the binding to choose the path based on userId validity, which is clean and safe.
  2. Step 2: Evaluate other options

    <a *ngIf="userId" [routerLink]="['/user', userId]">User Details</a> hides the link if userId is falsy, which may be okay but removes the link entirely. <a [routerLink]="['/user', userId || 'default']">User Details</a> uses a fallback string which might not be desired. <a [routerLink]="/user/{{userId}}">User Details</a> uses interpolation inside the binding expression, which is invalid template syntax.
  3. Final Answer:

    <a [routerLink]="userId ? ['/user', userId] : ['/user']">User Details</a> -> Option A
  4. Quick Check:

    Use ternary inside binding for conditional paths [OK]
Quick Trick: Use ternary operator inside [routerLink] for conditions [OK]
Common Mistakes:
MISTAKES
  • Using interpolation inside routerLink attribute
  • Hiding link instead of changing path
  • Using fallback strings that may confuse routing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes