0
0
Angularframework~30 mins

Dynamic component loading in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic Component Loading in Angular
📖 Scenario: You are building a dashboard in Angular where different widgets can appear based on user choice. You want to load these widgets dynamically without hardcoding them in the template.
🎯 Goal: Create an Angular standalone component that dynamically loads one of two simple widget components based on a configuration variable.
📋 What You'll Learn
Create two simple standalone widget components named WidgetOneComponent and WidgetTwoComponent.
Create a main standalone component named DashboardComponent that will load one of the widgets dynamically.
Use Angular's ViewContainerRef and ComponentFactoryResolver or the modern createComponent method to load the widget.
Add a configuration variable selectedWidget in DashboardComponent to choose which widget to load.
Ensure the dynamic component is loaded inside a container element with a template reference variable.
💡 Why This Matters
🌍 Real World
Dynamic component loading is useful in dashboards, form builders, and plugin systems where UI parts change based on user actions or configuration.
💼 Career
Understanding dynamic component loading helps you build flexible Angular apps and is a common requirement in enterprise Angular development.
Progress0 / 4 steps
1
Create two standalone widget components
Create two standalone Angular components named WidgetOneComponent and WidgetTwoComponent. Each should have a simple template: <p>This is Widget One</p> and <p>This is Widget Two</p> respectively.
Angular
Need a hint?

Use @Component decorator with standalone: true and simple templates for each widget.

2
Add configuration variable in DashboardComponent
Create a standalone Angular component named DashboardComponent. Inside it, add a public variable called selectedWidget and set it to the string 'one'.
Angular
Need a hint?

Define selectedWidget as a public property initialized to 'one'.

3
Add ViewChild and load dynamic component
In DashboardComponent, import ViewChild, ViewContainerRef, and AfterViewInit. Add a @ViewChild property named widgetContainer of type ViewContainerRef. Implement AfterViewInit and inside ngAfterViewInit(), write code to dynamically create WidgetOneComponent if selectedWidget is 'one', else create WidgetTwoComponent inside widgetContainer.
Angular
Need a hint?

Use @ViewChild to get the container, clear it, then use createComponent to load the chosen widget.

4
Add imports for dynamic components in DashboardComponent
In DashboardComponent, add import statements for WidgetOneComponent and WidgetTwoComponent so they can be used in createComponent. Also, add these components to the imports array in the @Component decorator of DashboardComponent.
Angular
Need a hint?

Import the widget components and add them to the imports array in @Component.