0
0
Angularframework~30 mins

Lazy loading standalone components in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Lazy Loading Standalone Components in Angular
📖 Scenario: You are building a simple Angular app that shows different messages on demand. To keep the app fast, you want to load the message components only when the user asks for them.
🎯 Goal: Build an Angular app that lazy loads two standalone components: WelcomeComponent and GoodbyeComponent. The app should load these components only when the user clicks their buttons.
📋 What You'll Learn
Create two standalone components: WelcomeComponent and GoodbyeComponent
Create a main AppComponent with buttons to load each component
Use Angular's loadComponent method to lazy load the components on button click
Display the loaded component inside a container in AppComponent
💡 Why This Matters
🌍 Real World
Lazy loading standalone components helps keep Angular apps fast by loading only what the user needs when they need it.
💼 Career
Understanding lazy loading is important for building scalable Angular applications that perform well and provide a good user experience.
Progress0 / 4 steps
1
Create the standalone components
Create two standalone components named WelcomeComponent and GoodbyeComponent. Each should have a simple template: WelcomeComponent displays "Welcome to the app!" and GoodbyeComponent displays "Goodbye! See you soon."
Angular
Need a hint?

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

2
Set up the AppComponent with buttons and container
Create a standalone AppComponent with two buttons labeled "Show Welcome" and "Show Goodbye". Add a container element with a template reference variable #container where the lazy loaded components will appear.
Angular
Need a hint?

Use @ViewChild to get the container reference and add buttons with click handlers.

3
Implement lazy loading logic for components
In AppComponent, implement the methods showWelcome() and showGoodbye(). Use this.container.clear() to clear the container, then use this.container.loadComponent() with dynamic imports to lazy load WelcomeComponent and GoodbyeComponent respectively.
Angular
Need a hint?

Use dynamic import() inside loadComponent() to lazy load each component.

4
Complete the app with bootstrap and imports
Add the necessary imports and bootstrap code to run the Angular app with AppComponent as the root. Import BrowserModule and bootstrap AppComponent in main.ts.
Angular
Need a hint?

Use bootstrapApplication(AppComponent) to start the app and import BrowserModule in AppComponent.