Looks like you're stuck. Need a hand?

Share This Tutorial

Views 23

Angular 18

Date  |  Category Programming
...
...
Back Back

Getting Started with Angular 18: New Features and Best Practices

Angular 18 introduces exciting new features and improvements to help developers build faster, more efficient applications. This tutorial covers the key enhancements and provides a step-by-step guide to leveraging them.

1. Zoneless Change Detection (Experimental)

Angular 18 introduces an experimental zoneless change detection system, dropping the dependency on zone.js. This feature offers faster renders, simpler stack traces, and native async/await support without down-leveling the CLI.

Why Use Zoneless Change Detection?

How to Opt-In

To enable zoneless change detection:

// In your main.ts file
import { provideExperimentalZonelessChangeDetection } from '@angular/core';
bootstrapApplication(AppComponent, {
  providers: [
    provideExperimentalZonelessChangeDetection()
  ]
});

Remove zone.js from your polyfills:

// polyfills.ts
// Remove or comment out the following line
// import 'zone.js/dist/zone';  // Included with angular-in-memory-web-api

2. Coalescing Scheduler

The coalescing scheduler is now enabled by default in new Angular 18 applications. This feature reduces unnecessary change detection cycles by coalescing multiple events into a single cycle.

What is Event Coalescing?

Example Configuration

To manually configure the coalescing scheduler:

// In your application module (e.g., app.module.ts)
import { CoalescingSchedulerConfig } from '@angular/core';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    {
      provide: CoalescingSchedulerConfig,
      useValue: {
        coalescingSchedulerEnabled: true
      }
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

3. Material 3 Stable

Angular Material 3 (M3) is now stable. It includes a complete set of M3 components and refreshed documentation.

Key Features:

Example of Using an M3 Component

Update your Angular Material to M3:

ng add @angular/[email protected]

Use an M3 component in your template:

<button matButton color="primary">
  Primary Button
</button>

For more details, refer to the Angular Material Documentation.

4. Deferrable Views

Deferrable views allow you to lazy-hydrate heavy UI chunks by using the @defer block. This feature helps reduce your initial bundle size.

Why Use Deferrable Views?

Example of Defer Block Usage

<!-- my.component.html -->
<div *ngFor="let item of items" class="item">
  <defer>
    <heavy-component *ngIf="isInView(item)"></heavy-component>
  </defer>
</div>
// my.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-my',
  templateUrl: './my.component.html'
})
export class MyComponent {
  isInView(item: any) {
    // Custom logic to determine if the item is in view
    return true; // Example implementation
  }
}

5. Signals API (Developer Preview)

Angular 18 introduces the Signals API (developer preview), offering fine-grained reactive primitives integrated with templates.

Key Features:

Example of Using Signals API

// item.component.ts
import { signal, computed, effect } from '@angular/core';

@Component({
  selector: 'app-item',
  template: `
    <div>
      <p *ngFor="let comment of comments">
        {{ comment }}
      </p>
    </div>
  `
})
export class ItemComponent {
  private _comments = signal(['Comment 1', 'Comment 2']);

  public get comments() {
    return this._comments();
  }

  private _filteredComments = computed(() => 
    this.comments.filter(comment => comment.includes('Comment'))
  );

  effect(() => {
    console.log('Comments updated:', this.comments);
  });
}
<!-- app.component.html -->
<div *ngFor="let item of items">
  <app-item [comments]="item.comments"></app-item>
</div>

6. SSR Improvements

Angular 18 includes significant improvements for Server-Side Rendering (SSR), including hydration for i18n, Angular Material, and event replay matching Google Search's infrastructure.

Key Enhancements:

Example of Event Replay in SSR

<!-- sample.component.html -->
<button (click)="handleClick()">
  Click Me
</button>
// sample.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html'
})
export class SampleComponent {
  handleClick() {
    console.log('Button clicked!');
  }
}

For more details, refer to the Angular Universal Documentation.

7. Upgrading to Angular 18

Upgrading to Angular 18 is straightforward. Follow these steps:

Steps to Upgrade

  1. Update Angular Core and CLI:
ng update @angular/core@18 @angular/cli@18
  1. Opt-in to Experimental Zoneless Change Detection:
// In your main.ts file
import { provideExperimentalZonelessChangeDetection } from '@angular/core';

bootstrapApplication(AppComponent, {
  providers: [
    provideExperimentalZonelessChangeDetection()
  ]
});
  1. Remove zone.js from polyfills:
// polyfills.ts
// Remove or comment out the following line
// import 'zone.js/dist/zone';  // Included with angular-in-memory-web-api
  1. Run your tests to ensure everything works as expected.

For detailed upgrade instructions, visit the Angular Update Guide.

Conclusion

Angular 18 delivers powerful features that enhance performance, simplify development, and offer new ways to manage state and UI. By following this guide, you can leverage the latest improvements to build faster, more efficient Angular applications. Start experimenting with zoneless change detection, Signals API, and deferrable views today!