Bird
0
0

In Angular, when you need to dynamically load multiple different components based on runtime conditions, which technique best manages component references and lifecycle?

hard📝 Conceptual Q8 of 15
Angular - Advanced Patterns
In Angular, when you need to dynamically load multiple different components based on runtime conditions, which technique best manages component references and lifecycle?
AManually manipulate the DOM to insert component HTML strings
BPreload all components in the template and toggle their visibility with *ngIf
CUse multiple <ng-template> elements with static component declarations and switch between them using CSS
DUse a single ViewContainerRef and maintain a map of component types to dynamically create and destroy components as needed
Step-by-Step Solution
Solution:
  1. Step 1: Understand dynamic component management

    Loading components dynamically requires creating and destroying them at runtime.
  2. Step 2: Use ViewContainerRef effectively

    A single ViewContainerRef can create components dynamically and keep track of their references.
  3. Step 3: Maintain a map for efficient handling

    Mapping component types allows easy creation and destruction based on user input or conditions.
  4. Final Answer:

    Use a single ViewContainerRef and maintain a map of component types to dynamically create and destroy components as needed -> Option D
  5. Quick Check:

    Dynamic creation + lifecycle management = map + ViewContainerRef [OK]
Quick Trick: Manage dynamic components with ViewContainerRef and a type map [OK]
Common Mistakes:
  • Preloading all components wastes resources
  • Using CSS to hide components does not destroy them
  • Direct DOM manipulation bypasses Angular's rendering

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes