0
0
Angularframework~10 mins

Dynamic component loading in Angular - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Dynamic component loading
Start
User triggers load
Inject ViewContainerRef
Create component dynamically
Insert component into view
Component renders
User interacts or unloads
Destroy component if needed
End
This flow shows how Angular dynamically creates and inserts a component into the view when triggered, then optionally destroys it later.
Execution Sample
Angular
import { Component, ViewChild, ViewContainerRef, ComponentRef } from '@angular/core';

@Component({
  selector: 'app-dynamic',
  template: '<p>Dynamic Component Loaded!</p>'
})
export class DynamicComponent {}

@Component({ selector: 'app-host', template: `<button (click)="load()">Load</button><ng-template #container></ng-template>` })
export class HostComponent {
  @ViewChild('container', { read: ViewContainerRef }) vcr!: ViewContainerRef;

  load() {
    const comp = this.vcr.createComponent(DynamicComponent);
  }
}
This code shows a button that, when clicked, dynamically creates and inserts a component into the view container.
Execution Table
StepTriggerActionComponentRef CreatedViewContainerRef StateRendered Output
1App startsHostComponent initializedNoneEmptyButton 'Load' visible
2User clicks 'Load'load() method calledDynamicComponent instance createdContains 1 componentButton 'Load' + DynamicComponent rendered
3User clicks 'Load' againload() called againAnother DynamicComponent instance createdContains 2 componentsButton 'Load' + 2 DynamicComponents rendered
4User closes appComponents destroyedAll component refs destroyedEmptyOnly button or app closes
5EndNo further actionNoneEmpty or cleanedNo dynamic components visible
💡 Execution stops when user closes app or no more dynamic components are created.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
vcr (ViewContainerRef)Empty1 component2 componentsEmptyEmpty
comp (ComponentRef)None1 instance2 instances (last created)NoneNone
Key Moments - 3 Insights
Why does clicking 'Load' multiple times add more components instead of replacing the old one?
Because each call to createComponent adds a new component to the ViewContainerRef without clearing previous ones, as shown in execution_table rows 2 and 3.
How does Angular know where to insert the dynamic component?
Angular uses the ViewContainerRef injected in the host component, which points to the <ng-template> location in the template, as seen in the code sample.
What happens if we don't destroy the dynamic components?
They remain in the view and consume memory; proper cleanup is needed to avoid leaks, as implied in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of ViewContainerRef after the user clicks 'Load' twice?
AContains 2 components
BContains 1 component
CEmpty
DContains no components
💡 Hint
Check execution_table row 3 under 'ViewContainerRef State'
At which step are all dynamic components destroyed?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at execution_table row 4 describing destruction
If we want only one dynamic component visible at a time, what should we do before creating a new one?
ADo nothing, Angular handles it automatically
BCall vcr.clear() to remove existing components
CCreate multiple components anyway
DReload the whole app
💡 Hint
Refer to key_moments about multiple components accumulating in ViewContainerRef
Concept Snapshot
Dynamic component loading in Angular:
- Inject ViewContainerRef where you want to insert
- Call createComponent() to add component dynamically
- Multiple calls add multiple components unless cleared
- Use vcr.clear() to remove old components
- Destroy components to free resources
Full Transcript
Dynamic component loading in Angular means creating and inserting components into the view at runtime instead of static templates. The process starts when the user triggers an action, like clicking a button. Angular uses a ViewContainerRef, which points to a placeholder in the template, to insert the new component. Each call to createComponent adds a new instance inside the container. Without clearing, multiple components accumulate. Proper cleanup involves destroying components when no longer needed. This visual trace shows the state changes step-by-step, helping beginners understand how dynamic components appear and disappear in the app.