Modern Angular Architecture: Standalone & Control Flow
7 min read
Modern Angular Architecture: Standalone & Control Flow
Course: Angular
Topic ID: 9
👋 Welcome to the "No-Module" Era
Welcome, developer. 🧘♂️ Take a deep breath. Can you smell that? It’s the scent of fresh, clean code. For years, Angular developers lived in a complex web called the NgModule Matrix. We spent hours figuring out which module owned which component, why a pipe wasn't found, and creating SharedModule dumps that contained half the universe.
Today, we leave that baggage behind. We are entering the age of Modern Angular Architecture. It is minimalist, performant, and strangely enough... simple.
Fun Fact: NgModules were originally introduced to help the Angular compiler (ngc) understand how your templates fit together. In the early days (pre-2016), they were a necessary evil for performance. Today, with the Ivy compiler, they are like keeping a fax machine when you have email—nostalgic, but unnecessary. 📠
1. Standalone Components: Developing Without NgModules
🧱 The Concept
The Problem: In the past, to create a simple "Hello World" component, you needed:
- The Component file.
- An NgModule file.
- To add the component to
declarations. - To add the component to
exports(if shared). - To import
CommonModuleor others.
It was a lot of boilerplate (ceremony) for very little logic.
The Solution: Standalone Components.
A component that knows its own dependencies. It doesn't need a parent module to tell it what pipes or directives it can use. It is self-contained.
🛠️ Hands-on Practice
To make a component standalone, you simply add standalone: true to its decorator and import what it needs directly.
The Old Way (Module-based)
// user-card.component.ts
@Component({
selector: 'app-user-card',
template: `<div>{{ user.name | uppercase }}</div>`
})
export class UserCardComponent { ... }
// app.module.ts (The "Middleman")
@NgModule({
declarations: [UserCardComponent],
imports: [CommonModule],
exports: [UserCardComponent]
})
export class AppModule { }The Modern Way (Standalone) ✨
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common'; // Still needed for pipes like uppercase
@Component({
selector: 'app-user-card',
standalone: true, // 👈 The magic switch
imports: [CommonModule], // 👈 Direct imports!
template: `
<div class="card">
<h2>{{ name | uppercase }}</h2>
</div>
`
})
export class UserCardComponent {
name = 'Angular Ninja';
}🚀 Bootstrapping the App
Since we don't have AppModule, how do we start the app? We use bootstrapApplication.
main.ts:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { provideRouter } from '@angular/router';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
// Add other global providers here (HTTP, Animations, etc.)
]
}).catch(err => console.error(err));Note: This is strictly the modern standard. If you see platformBrowserDynamic().bootstrapModule(AppModule), you are looking at legacy code.
2. Modern Control Flow: @if, @for, and @empty
🚦 The Concept
The Problem: Structural directives like *ngIf and *ngFor were actually just syntax sugar for <ng-template>. They required importing CommonModule, added runtime overhead, and had clunky syntax for else blocks (remember creating an ng-template #elseBlock? 🤮).
The Solution: Built-in Control Flow Blocks.
These are not directives. They are part of the template language itself. They are faster, type-safe, and don't require imports.
🛠️ Hands-on Practice
@if (Conditional Rendering)
Clean, readable, and supports else if.
<!-- Old Way -->
<div *ngIf="isLoggedIn; else loginTpl">
Welcome User!
</div>
<ng-template #loginTpl>
<button>Login</button>
</ng-template>
<!-- Modern Way -->
@if (isLoggedIn) {
<div class="user-dash">
Welcome User!
</div>
} @else if (isLoading) {
<p>Checking credentials...</p>
} @else {
<button>Login</button>
}@for (Loops) & @empty
The @for block is a game-changer. It requires a track expression (which forces performance best practices) and includes a built-in @empty block for when your array has zero items. No more checking items.length === 0 manually!
<ul>
<!--
track: Essential for performance.
It tells Angular how to identify items (like distinct ID).
Use $index or item.id.
-->
@for (user of users; track user.id; let idx = $index, c = $count) {
<li [class.even]="idx % 2 === 0">
{{ idx + 1 }} / {{ c }} - {{ user.name }}
</li>
} @empty {
<!-- Renders if 'users' is null, undefined, or [] -->
<li class="empty-state">No users found! 🕵️♂️</li>
}
</ul>Why it's better:
- Up to 90% faster runtime performance than
*ngForin benchmarks. - No need to import
CommonModuleorNgFor.
3. Deferred Loading: Using @defer for Performance
⏳ The Concept
The Problem: Web apps are getting heavy. Usually, we load the entire page content at once, even parts the user can't see yet (like a heavy comments section at the bottom of the page). Lazy loading routes helped, but lazy loading parts of a template was extremely hard.
The Solution: Deferrable Views (@defer).
This allows you to wrap a section of your template and tell Angular: "Don't load the JavaScript for this code yet. Wait until X happens."
🛠️ Hands-on Practice
The @defer block works with Triggers.
<!--
The content inside @defer is NOT loaded initially.
It is fetched from the server only when the trigger fires.
-->
@defer (on viewport) {
<app-heavy-chart></app-heavy-chart>
} @placeholder {
<!-- Shown immediately until the trigger fires -->
<div class="skeleton-loader">Loading Chart area...</div>
} @loading (minimum 1s) {
<!-- Shown WHILE the chunk is being fetched from network -->
<div class="spinner">Fetching data...</div>
} @error {
<!-- Shown if the network request fails -->
<p>Failed to load the chart. Check connection.</p>
}🔮 Common Triggers (The Magic Spells)
You can mix and match these!
| Trigger | Description | Use Case |
|---|---|---|
on idle |
Loads when browser is doing nothing (Default). | Non-critical UI that should be ready soon. |
on viewport |
Loads when the placeholder enters the screen. | Heavy components "below the fold" (footer, comments). |
on interaction |
Loads when user clicks/types on the placeholder. | Chat widgets, complex forms hidden behind a button. |
on hover |
Loads when mouse hovers. | Tooltips or hover-menus. |
on timer(5s) |
Loads after specific time. | Rotators or popups. |
Example of interaction:
@defer (on interaction(loadButton)) {
<app-chat-widget />
}
<button #loadButton>Open Chat</button>4. Migrating Traditional Apps to Standalone Architecture
🚧 The Strategy
You don't have to rewrite your app overnight. Angular allows a Hybrid state. You can have AppModule importing Standalone Components, and Standalone Components importing NgModules.
Industry Standard:
- New Features First: Build all new features as Standalone.
- Leaves to Root: Migrate "leaf" components (dumb UI components) first, then work your way up to Feature Modules, and finally the App Component.
🤖 The Automatic Migration (The Easy Way)
The Angular team provided incredible schematics (scripts) to do the heavy lifting.
Step 1: Convert to Standalone
Run this in your terminal:
ng generate @angular/core:standaloneSelect "Convert all components, directives and pipes to standalone".
This adds standalone: true and calculates the imports array for every component.
Step 2: Remove Unnecessary Modules
Run the command again:
ng generate @angular/core:standaloneSelect "Remove unnecessary NgModule classes".
This deletes modules that are no longer needed because their components are now self-sufficient.
Step 3: Bootstrap
Run the command a third time:
ng generate @angular/core:standaloneSelect "Bootstrap the project using standalone APIs".
This converts your main.ts and deletes AppModule.
🧹 Manual Clean-up Checklist
Even with automation, check these:
- Routing: Convert
loadChildrento the new syntax.- Old:
loadChildren: () => import('./user/user.module').then(m => m.UserModule) - New:
loadChildren: () => import('./user/user.routes').then(m => m.USER_ROUTES)
- Old:
- Test Files:
spec.tsfiles might need updates toimportsinstead ofdeclarationsinTestBed.
📚 Resources for Extra Reading
- Official Angular Standalone Guide
- Control Flow Syntax Documentation
- Deferrable Views (@defer) Guide
- Angular Migration Guide
End of Topic 9. Keep your bundles small and your templates clean. Happy coding! ☕
Challenge
Challenge: Modernize the Product List Component
Your task is to refactor and complete a ProductListComponent using Angular's modern, standalone architecture and new control flow syntax. You will implement features to display a list of products, handle empty states, show conditional UI elements, and optimize performance with deferred loading.
Requirements:
- Convert to Standalone: Modify the
@Componentdecorator to makeProductListComponenta standalone component. It should not require anNgModule. - Render Product List: Use the
@forcontrol flow block to iterate over theproductsarray. You must use the product'sidproperty for thetrackexpression. - Display Product Details: For each product in the list, display its
nameandprice. - Handle Empty State: If the
productsarray is empty, the@forblock should use its built-in@emptystate to display a single paragraph with the text:No products found.. - Conditional Badge: Use the
@ifcontrol flow block to display a<span>element with the textON SALE!next to the product's price, but only if itsonSaleproperty istrue. - Deferred Loading for Reviews: Implement a deferred loading section for customer reviews using
@defer. This section should be triggeredon interactionwith a button. - Deferred Content: Inside the main
@deferblock, display a heading<h3>Customer Reviews</h3>and then iterate through the product'sreviewsarray to display each review. - Placeholder: The
@deferblock must have a@placeholderthat contains a<button>with the textView Reviews. - Loading State: The
@deferblock must also have a@loadingstate that displays a paragraph with the textLoading reviews....
Expected result
Your final code should be a single TypeScript file containing a standalone Angular component.
The @Component decorator must be updated to include standalone: true. No imports array is necessary because the new control flow syntax is built-in.
The template string should contain the following structure:
- An
@forblock that iterates over theproductsarray, withtrack product.id. - Inside the
@forblock, HTML elements to display theproduct.nameandproduct.price. - An
@if (product.onSale)block nested inside the@forloop that conditionally renders a<span>with the textON SALE!. - An
@emptyblock at the end of the@forblock that displays<p>No products found.</p>. - A
@defer (on interaction)block for each product. - Inside the
@deferblock, there must be a@placeholdercontaining a<button>View Reviews</button>. - There must also be a
@loadingblock showing<p>Loading reviews...</p>. - The main content of the
@deferblock should render the product's reviews, for example, by using another@forloop.