Bird
Raised Fist0
Angularframework~15 mins

Dynamic component loading in Angular - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Dynamic component loading
What is it?
Dynamic component loading in Angular means creating and showing components on the screen while the app is running, not just when the app starts. Instead of having all components fixed in the template, you can decide which component to show based on user actions or data. This helps make apps more flexible and efficient by loading only what is needed.
Why it matters
Without dynamic loading, apps would have to include all components upfront, making them slower and less responsive. Dynamic loading saves resources and improves user experience by showing components only when necessary. It also allows building features like popups, tabs, or dashboards that change content on the fly.
Where it fits
Before learning dynamic component loading, you should understand Angular components, templates, and basic dependency injection. After mastering it, you can explore advanced topics like lazy loading modules, Angular signals, and server-side rendering with dynamic content.
Mental Model
Core Idea
Dynamic component loading is like choosing and placing a puzzle piece exactly when and where you need it during the game, instead of having all pieces fixed on the board from the start.
Think of it like...
Imagine a restaurant kitchen where the chef prepares dishes only when customers order them, instead of cooking everything in advance. This saves time, space, and ingredients, just like dynamic loading saves app resources by creating components only when needed.
┌───────────────────────────────┐
│       Host Component           │
│  ┌─────────────────────────┐  │
│  │ Dynamic Component Slot   │◄─┤ Insert component here
│  └─────────────────────────┘  │
└───────────────────────────────┘
          ▲
          │
  ┌───────────────────┐
  │ Component Factory  │
  └───────────────────┘
          ▲
          │
  ┌───────────────────┐
  │ Component Class    │
  └───────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Angular Components
🤔
Concept: Learn what Angular components are and how they display content using templates.
Angular components are building blocks of the UI. Each has a TypeScript class and an HTML template. The class controls data and behavior, while the template shows what users see. Components are usually declared in templates with tags like .
Result
You can create and display static components in your app.
Understanding components is essential because dynamic loading means creating these building blocks on demand.
2
FoundationTemplates and ViewContainerRef Basics
🤔
Concept: Learn how Angular templates and ViewContainerRef let you control where components appear.
ViewContainerRef is a handle to a spot in the template where you can add or remove components dynamically. You get it by injecting it in your component or directive. This lets you tell Angular exactly where to place new components.
Result
You know how to mark a place in your template to insert components later.
Knowing how to target insertion points is key to dynamic component placement.
3
IntermediateCreating Components Dynamically
🤔Before reading on: do you think Angular creates dynamic components by cloning existing HTML or by instantiating classes? Commit to your answer.
Concept: Learn how to create component instances at runtime using Angular's ComponentFactoryResolver or the new createComponent API.
Angular lets you create components dynamically by calling createComponent with the component class and a ViewContainerRef. This builds the component instance and inserts its view into the DOM at the specified spot.
Result
You can add new components to the page while the app runs, not just at startup.
Understanding that Angular creates real component instances, not just HTML snippets, explains how dynamic components behave fully like static ones.
4
IntermediatePassing Data to Dynamic Components
🤔Before reading on: do you think you can pass inputs to dynamic components the same way as static ones? Commit to your answer.
Concept: Learn how to set input properties on dynamically created components to customize their behavior.
After creating a component dynamically, you get its instance from the componentRef. You can then set input properties directly on this instance before Angular runs change detection to update the view.
Result
Dynamic components can receive data and behave differently based on inputs.
Knowing how to pass data keeps dynamic components flexible and interactive.
5
IntermediateCleaning Up Dynamic Components
🤔
Concept: Learn how to remove dynamic components and avoid memory leaks.
When you create components dynamically, Angular does not automatically remove them. You must call destroy() on the componentRef or clear the ViewContainerRef to remove components and free resources.
Result
Your app stays efficient and avoids performance problems.
Understanding cleanup prevents common bugs and resource waste in dynamic loading.
6
AdvancedUsing Angular Signals with Dynamic Components
🤔Before reading on: do you think dynamic components can react automatically to reactive state changes? Commit to your answer.
Concept: Learn how Angular's reactive signals can update dynamic components automatically when data changes.
Angular signals let you create reactive data sources. When you pass signals as inputs to dynamic components, those components update their views automatically when the signals change, without manual refresh.
Result
Dynamic components become reactive and efficient, improving user experience.
Knowing how signals integrate with dynamic loading unlocks modern reactive UI patterns.
7
ExpertOptimizing Dynamic Loading with Lazy Modules
🤔Before reading on: do you think dynamic components always come from the main app bundle? Commit to your answer.
Concept: Learn how to load components from separate modules only when needed, reducing initial app size.
Angular supports lazy loading modules that contain components. You can import these modules dynamically with import() and then create components from them. This delays loading code until the user needs it, speeding up startup.
Result
Your app loads faster and uses less memory by loading components on demand.
Understanding lazy loading with dynamic components is key to building scalable, performant Angular apps.
Under the Hood
When you call createComponent, Angular uses its internal ComponentFactory to instantiate the component class, create its view, and attach it to the specified ViewContainerRef. Angular's change detection then runs to update the view. The component instance lives in memory and behaves like any other component, with lifecycle hooks and dependency injection.
Why designed this way?
Angular was designed to separate component logic from rendering. Dynamic loading needed a way to create full component instances at runtime, not just HTML fragments, to keep features like lifecycle hooks and DI working. Using factories and ViewContainerRef provides a flexible, consistent API that fits Angular's architecture.
┌───────────────────────────────┐
│       createComponent()        │
├─────────────┬─────────────────┤
│             │                 │
│   Component Factory            │
│             │                 │
│  ┌──────────▼───────────┐     │
│  │ Instantiate Component │     │
│  └──────────┬───────────┘     │
│             │                 │
│  ┌──────────▼───────────┐     │
│  │ Create Component View │     │
│  └──────────┬───────────┘     │
│             │                 │
│  ┌──────────▼───────────┐     │
│  │ Attach to ViewContainer │   │
│  └──────────┬───────────┘     │
│             │                 │
│  ┌──────────▼───────────┐     │
│  │ Run Change Detection  │     │
│  └──────────────────────┘     │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think dynamic components are just HTML snippets inserted into the DOM? Commit to yes or no.
Common Belief:Dynamic components are just pieces of HTML added to the page like innerHTML.
Tap to reveal reality
Reality:Dynamic components are full Angular component instances with their own logic, lifecycle, and change detection.
Why it matters:Treating them as plain HTML leads to missing lifecycle hooks and broken behavior, causing bugs and inconsistent UI.
Quick: Do you think Angular automatically cleans up dynamic components when you remove them from the view? Commit to yes or no.
Common Belief:Angular automatically destroys dynamic components when they are removed from the DOM.
Tap to reveal reality
Reality:You must manually destroy dynamic components or clear their container to avoid memory leaks.
Why it matters:Ignoring cleanup causes memory leaks and performance degradation in long-running apps.
Quick: Do you think you can pass inputs to dynamic components exactly like static ones in templates? Commit to yes or no.
Common Belief:Inputs to dynamic components work the same way as static components in templates.
Tap to reveal reality
Reality:You must set input properties directly on the component instance after creation and trigger change detection if needed.
Why it matters:Assuming inputs work automatically causes data not to appear or update, confusing developers.
Quick: Do you think dynamic component loading always increases app size? Commit to yes or no.
Common Belief:Dynamic loading always makes the app bigger because it adds more code.
Tap to reveal reality
Reality:Dynamic loading can reduce initial app size by loading components only when needed, especially with lazy modules.
Why it matters:Misunderstanding this prevents developers from optimizing app performance and startup time.
Expert Zone
1
Dynamic components share the same injector hierarchy as their host, so dependency injection behaves consistently, but subtle injector boundaries can cause unexpected service instances.
2
Change detection for dynamic components may require manual triggering in some cases, especially when inputs are set after creation, to ensure the view updates correctly.
3
Using Angular signals with dynamic components can simplify reactive updates but requires understanding signal scopes and lifecycle to avoid stale data or memory leaks.
When NOT to use
Avoid dynamic component loading when the UI structure is static and known upfront, as it adds complexity and overhead. For simple conditional rendering, use *ngIf or *ngSwitch. For large feature modules, prefer lazy loading entire modules instead of individual components to optimize performance.
Production Patterns
In real apps, dynamic loading is used for modal dialogs, tabs, dashboards with user-customizable widgets, and plugin architectures. Experts combine it with lazy loading and Angular signals to build scalable, reactive, and fast applications that load only what users need.
Connections
Lazy Loading Modules
Dynamic component loading often builds on lazy loading modules to load components only when needed.
Understanding lazy loading modules helps optimize dynamic loading by reducing initial bundle size and improving app startup speed.
Dependency Injection
Dynamic components rely on Angular's dependency injection to get services and data, just like static components.
Knowing how DI works ensures dynamic components receive correct dependencies and behave consistently.
Factory Design Pattern
Dynamic component loading uses the factory pattern to create component instances at runtime.
Recognizing this pattern connects Angular's dynamic loading to a common software design principle, aiding deeper understanding.
Common Pitfalls
#1Creating dynamic components without specifying the insertion point.
Wrong approach:const componentRef = this.componentFactoryResolver.resolveComponentFactory(MyComponent).create(this.injector);
Correct approach:const componentRef = this.viewContainerRef.createComponent(MyComponent);
Root cause:Not using ViewContainerRef to insert the component into the DOM causes the component to exist but not appear.
#2Forgetting to destroy dynamic components when no longer needed.
Wrong approach:const componentRef = this.viewContainerRef.createComponent(MyComponent); // No destroy call later
Correct approach:const componentRef = this.viewContainerRef.createComponent(MyComponent); componentRef.destroy();
Root cause:Assuming Angular cleans up automatically leads to memory leaks and performance issues.
#3Setting inputs on dynamic components before creation.
Wrong approach:this.viewContainerRef.createComponent(MyComponent, { inputs: { title: 'Hello' } });
Correct approach:const componentRef = this.viewContainerRef.createComponent(MyComponent); componentRef.instance.title = 'Hello'; componentRef.changeDetectorRef.detectChanges();
Root cause:Inputs must be set on the instance after creation; the createComponent options object does not support inputs directly.
Key Takeaways
Dynamic component loading lets Angular apps create and show components during runtime, making UIs flexible and efficient.
It works by creating full component instances and inserting their views into specific places in the template using ViewContainerRef.
Passing data to dynamic components requires setting inputs on the component instance after creation and managing change detection.
Proper cleanup of dynamic components is essential to avoid memory leaks and keep the app performant.
Combining dynamic loading with lazy modules and Angular signals enables building scalable, reactive, and fast applications.

Practice

(1/5)
1. What is the main purpose of dynamic component loading in Angular?
easy
A. To add components to the view while the app is running
B. To statically declare all components in the template
C. To improve CSS styling of components
D. To replace Angular modules with components

Solution

  1. Step 1: Understand dynamic component loading

    Dynamic component loading means adding components to the app view during runtime, not just at compile time.
  2. Step 2: Compare options

    Only To add components to the view while the app is running describes adding components while the app runs. Other options describe static or unrelated concepts.
  3. Final Answer:

    To add components to the view while the app is running -> Option A
  4. Quick Check:

    Dynamic loading = add components at runtime [OK]
Hint: Dynamic loading means adding components during app run [OK]
Common Mistakes:
  • Confusing dynamic loading with static template declaration
  • Thinking it changes CSS or modules
  • Assuming it replaces Angular modules
2. Which Angular service is used to insert a dynamic component into the view?
easy
A. Renderer2
B. HttpClient
C. ViewContainerRef
D. NgModuleRef

Solution

  1. Step 1: Identify the service for dynamic insertion

    ViewContainerRef provides a container where components can be dynamically added or removed.
  2. Step 2: Eliminate other options

    Renderer2 is for DOM manipulation, HttpClient for HTTP calls, NgModuleRef for module references, none for dynamic component insertion.
  3. Final Answer:

    ViewContainerRef -> Option C
  4. Quick Check:

    Dynamic insertion uses ViewContainerRef [OK]
Hint: Use ViewContainerRef to insert dynamic components [OK]
Common Mistakes:
  • Choosing Renderer2 which is for DOM, not components
  • Confusing HttpClient with component loading
  • Using NgModuleRef incorrectly
3. Given this code snippet, what will be the output in the browser?
const componentRef = viewContainerRef.createComponent(MyComponent);
componentRef.instance.title = 'Hello';

Assuming MyComponent displays {{ title }} in its template.
medium
A. The component will load but title will be empty
B. The text 'Hello' will appear where the component is loaded
C. Nothing will appear because the component is not attached
D. An error because title is not a valid property

Solution

  1. Step 1: Understand createComponent and instance property

    createComponent adds the component to the view. Setting instance.title assigns the property used in the template.
  2. Step 2: Predict rendered output

    Since {{ title }} is displayed, and title is set to 'Hello', the text 'Hello' will appear.
  3. Final Answer:

    The text 'Hello' will appear where the component is loaded -> Option B
  4. Quick Check:

    Set instance property = visible text [OK]
Hint: Setting instance properties updates displayed content [OK]
Common Mistakes:
  • Thinking component is not attached after createComponent
  • Assuming property must be declared differently
  • Ignoring that instance properties affect template
4. What is wrong with this code snippet for dynamic component loading?
@ViewChild('container', { read: ViewContainerRef }) containerRef!: ViewContainerRef;

load() {
  const comp = this.containerRef.createComponent(SomeComponent);
  comp.instance.data = 'Test';
}
medium
A. ViewChild should not use read option
B. Using createComponent without importing ComponentFactoryResolver
C. Cannot assign data property on instance
D. Missing #container template reference in HTML

Solution

  1. Step 1: Check ViewChild usage

    ViewChild with #container expects a matching template reference variable in HTML.
  2. Step 2: Identify missing template reference

    If #container is missing in the template, containerRef will be undefined, causing runtime errors.
  3. Final Answer:

    Missing #container template reference in HTML -> Option D
  4. Quick Check:

    ViewChild needs matching template ref [OK]
Hint: Always add matching #ref in template for ViewChild [OK]
Common Mistakes:
  • Assuming ComponentFactoryResolver is needed in Angular 14+
  • Thinking instance properties can't be assigned
  • Misusing read option in ViewChild
5. You want to load different components dynamically based on user input. Which approach correctly handles this scenario in Angular?
hard
A. Use a single ViewContainerRef and call createComponent() with the chosen component type each time, clearing previous components
B. Declare all possible components in the template and use *ngIf to show/hide them
C. Create components manually with new keyword and append to DOM
D. Use Angular modules to switch components dynamically without ViewContainerRef

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]
Hint: 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