Learn Angular · 9/14

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:

  1. The Component file.
  2. An NgModule file.
  3. To add the component to declarations.
  4. To add the component to exports (if shared).
  5. To import CommonModule or 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)

typescript
// 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) ✨

typescript
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:

typescript
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.

html
<!-- 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!

html
<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:

  1. Up to 90% faster runtime performance than *ngFor in benchmarks.
  2. No need to import CommonModule or NgFor.

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.

html
<!-- 
  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:

html
@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:

  1. New Features First: Build all new features as Standalone.
  2. 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:

bash
ng generate @angular/core:standalone

Select "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:

bash
ng generate @angular/core:standalone

Select "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:

bash
ng generate @angular/core:standalone

Select "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 loadChildren to the new syntax.
    • Old: loadChildren: () => import('./user/user.module').then(m => m.UserModule)
    • New: loadChildren: () => import('./user/user.routes').then(m => m.USER_ROUTES)
  • Test Files: spec.ts files might need updates to imports instead of declarations in TestBed.

📚 Resources for Extra Reading


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:

  1. Convert to Standalone: Modify the @Component decorator to make ProductListComponent a standalone component. It should not require an NgModule.
  2. Render Product List: Use the @for control flow block to iterate over the products array. You must use the product's id property for the track expression.
  3. Display Product Details: For each product in the list, display its name and price.
  4. Handle Empty State: If the products array is empty, the @for block should use its built-in @empty state to display a single paragraph with the text: No products found..
  5. Conditional Badge: Use the @if control flow block to display a <span> element with the text ON SALE! next to the product's price, but only if its onSale property is true.
  6. Deferred Loading for Reviews: Implement a deferred loading section for customer reviews using @defer. This section should be triggered on interaction with a button.
  7. Deferred Content: Inside the main @defer block, display a heading <h3>Customer Reviews</h3> and then iterate through the product's reviews array to display each review.
  8. Placeholder: The @defer block must have a @placeholder that contains a <button> with the text View Reviews.
  9. Loading State: The @defer block must also have a @loading state that displays a paragraph with the text Loading 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 @for block that iterates over the products array, with track product.id.
  • Inside the @for block, HTML elements to display the product.name and product.price.
  • An @if (product.onSale) block nested inside the @for loop that conditionally renders a <span> with the text ON SALE!.
  • An @empty block at the end of the @for block that displays <p>No products found.</p>.
  • A @defer (on interaction) block for each product.
  • Inside the @defer block, there must be a @placeholder containing a <button>View Reviews</button>.
  • There must also be a @loading block showing <p>Loading reviews...</p>.
  • The main content of the @defer block should render the product's reviews, for example, by using another @for loop.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.