Bird
0
0

You want to load different components dynamically based on user input. Which approach correctly handles this scenario in Angular?

hard📝 Application Q15 of 15
Angular - Advanced Patterns
You want to load different components dynamically based on user input. Which approach correctly handles this scenario in Angular?
AUse a single ViewContainerRef and call <code>createComponent()</code> with the chosen component type each time, clearing previous components
BDeclare all possible components in the template and use *ngIf to show/hide them
CCreate components manually with new keyword and append to DOM
DUse Angular modules to switch components dynamically without ViewContainerRef
Step-by-Step Solution
Solution:
  1. Step 1: Understand dynamic component switching

    Using ViewContainerRef with createComponent allows loading different components at runtime by clearing old ones and adding new.
  2. Step 2: Evaluate other options

    Declare all possible components in the template and use *ngIf to show/hide them is static and less flexible. Create components manually with new keyword and append to DOM bypasses Angular and breaks framework rules. Use Angular modules to switch components dynamically without ViewContainerRef misunderstands modules' role.
  3. Final Answer:

    Use a single ViewContainerRef and call createComponent() with the chosen component type each time, clearing previous components -> Option A
  4. Quick Check:

    Dynamic switching = clear + createComponent [OK]
Quick Trick: Clear container then create chosen component dynamically [OK]
Common Mistakes:
  • Using static *ngIf instead of dynamic loading
  • Trying to create components with new keyword
  • Confusing modules with dynamic component loading

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes