Dynamic component loading lets you add components to your app while it is running. This helps show different content without rebuilding the whole page.
Dynamic component loading in Angular
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Angular
import { Component, ViewContainerRef, ComponentRef, inject } from '@angular/core'; @Component({ selector: 'app-dynamic-loader', template: `<ng-template #container></ng-template>`, standalone: true }) export class DynamicLoaderComponent { private viewContainerRef = inject(ViewContainerRef); loadComponent(component: any): ComponentRef<any> { this.viewContainerRef.clear(); return this.viewContainerRef.createComponent(component); } }
Use ViewContainerRef to control where the component appears.
Call createComponent() to add the component dynamically.
Examples
MyComponent inside the container.Angular
this.viewContainerRef.createComponent(MyComponent);AnotherComponent.Angular
this.viewContainerRef.clear(); this.viewContainerRef.createComponent(AnotherComponent);
MyComponent and sets an input property.Angular
const compRef = this.viewContainerRef.createComponent(MyComponent); compRef.instance.someInput = 'Hello';
Sample Program
This example shows a button that loads a simple component dynamically inside the page when clicked.
Angular
import { Component, ViewContainerRef, inject } from '@angular/core'; @Component({ selector: 'app-hello', template: `<p>Hello, I am a dynamic component!</p>`, standalone: true }) export class HelloComponent {} @Component({ selector: 'app-root', template: ` <button (click)="loadHello()">Load Hello Component</button> <ng-template #container></ng-template> `, standalone: true }) export class AppComponent { private viewContainerRef = inject(ViewContainerRef); loadHello() { this.viewContainerRef.clear(); this.viewContainerRef.createComponent(HelloComponent); } }
Important Notes
Always clear the container before loading a new component to avoid stacking.
You can pass data to the dynamic component by setting properties on compRef.instance.
Dynamic loading helps keep your app fast by loading only what is needed.
Summary
Dynamic component loading lets you add components while the app runs.
Use ViewContainerRef and createComponent() to load components.
This technique is useful for popups, dashboards, and conditional content.
Practice
1. What is the main purpose of dynamic component loading in Angular?
easy
Solution
Step 1: Understand dynamic component loading
Dynamic component loading means adding components to the app view during runtime, not just at compile time.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.Final Answer:
To add components to the view while the app is running -> Option AQuick 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
Solution
Step 1: Identify the service for dynamic insertion
ViewContainerRef provides a container where components can be dynamically added or removed.Step 2: Eliminate other options
Renderer2 is for DOM manipulation, HttpClient for HTTP calls, NgModuleRef for module references, none for dynamic component insertion.Final Answer:
ViewContainerRef -> Option CQuick 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?
Assuming
const componentRef = viewContainerRef.createComponent(MyComponent); componentRef.instance.title = 'Hello';
Assuming
MyComponent displays {{ title }} in its template.medium
Solution
Step 1: Understand createComponent and instance property
createComponent adds the component to the view. Settinginstance.titleassigns the property used in the template.Step 2: Predict rendered output
Since{{ title }}is displayed, andtitleis set to 'Hello', the text 'Hello' will appear.Final Answer:
The text 'Hello' will appear where the component is loaded -> Option BQuick 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
Solution
Step 1: Check ViewChild usage
ViewChild with#containerexpects a matching template reference variable in HTML.Step 2: Identify missing template reference
If#containeris missing in the template,containerRefwill be undefined, causing runtime errors.Final Answer:
Missing#containertemplate reference in HTML -> Option DQuick 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
Solution
Step 1: Understand dynamic component switching
Using ViewContainerRef with createComponent allows loading different components at runtime by clearing old ones and adding new.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.Final Answer:
Use a single ViewContainerRef and callcreateComponent()with the chosen component type each time, clearing previous components -> Option AQuick 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
