Latest Angular 18 Features with example

Angular 18 focused on features enhancing developer experience and application performance maintenance while also supporting the stability of existing projects. In Angular 18, the new features focus on improving performance and making programming smooth for developers.

The Angular 18 Features.

  1. Progressing Change Detection

  2. Shifting to Zoneless

  3. Native Async For Zoneless Apps

  4. Debugging and SSR Improvements

  5. Partial Hydration Strategy

  6. Control State Change Events

  7. Fallback Content for ng-content

  8. Route Redirects as Functions

1. Progressing Change Detection

Previously, Angular’s change detection triggering is responsible for a library called zone.js. The library has certain downsides including performance challenges. Angular has been trying for years to find a way that doesn’t rely on zone.js. Now they have shared an experimental API for Zoneless.

To make it work, include provideExperimentalZonelessChangeDetection to your bootstrap application:

bootstrapApplication(App, {
  providers: [
    provideExperimentalZonelessChangeDetection()
  ]
});

Once you have added the provider, remove zone.js from your polyfills in angular.json. 

The Ideal Way to Use Zoneless is with Signals in Component

@Component({
  ...
  template: `
    <h1>Hello from {{ name() }}!</h1>
    <button (click)="handleClick()">Go Zoneless</button>
  `,
})
export class App {
  protected name = signal('Angular');
  handleClick() {
    this.name.set('Zoneless Angular');
  }
}

What will zoneless do for developers?

  1. Enhanced composability for micro-frontends and interoperability with different frameworks

  2. Quicker initial render and runtime

  3. Improved debugging

  4. Better readable stack traces

2. Shifting to Zoneless

Zoneless is the core change in the evolution made by Angular. While the changes are made, they have made sure that all the existing APIs continue to work the same way and that there is good interoperability with everything new in Angular. 

Zoneless is one such story relating to interoperability. They also made sure that shifting your existing apps into zoneless stays simple. Therefore, if the components are compatible with ChangeDetectionStrategy.OnPush change detection strategy, your components are compatible with zoneless and the shift will be smooth.  

Default Coalescing

With the latest version of Angular, we will utilize the scheduler for zoneless apps and apps using zone.js by enabling coalescing. Zone coalescing by default is also enabled to minimize the number of change detection cycles. The significance of this feature is it is only available for new applications. The existing apps based on previous change detection behavior can cause bugs if enabled. 

If you want to go for event coalescing in the ongoing project, integrate NgZone provider in bootstrapApplicationbootstrapApplication:

bootstrapApplication(App, {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true })
  ]
});

3. Native Async For Zoneless Apps

One of the APIs that zone.js can’t monkey patch is the async/await, despite being able to intercept many browsers to plug Angular’s change detection in. Thus, they have leveled down to promises via the Angular CLI. 

Today if you build an app by using the experimental zoneless change detection Angular CLI, it will use the native async without downleveling it to promises. This will lead to small bundles and enhanced debugging.  

Signal APIs in Developer Preview

The new signal inputs, a new output syntax, and signal-based queries were all introduced in Angular 17.1 and 17.2. The signal guide has all the insights on how to use the APIs.

Things that Got Stable in Angular 18

Stabilized Material 3



The beta or experimental version of Material 3 was introduced a few months ago. Since then they have taken continuous feedback from developers and refined all the Material 3 components. Now the version can be considered stable. 

For example, 

If you wish to define or change the theme, you can use the below code:

@use '@angular/material' as mat;
$theme: mat.define-theme((
  color: (
    theme-type: dark,
    primary: mat.$violet-palette,
  ),
  typography: (
    brand-family: 'Comic Sans',
    bold-weight: 900
  ),
  density: (
    scale: -1
  )
));
Customize the theme with:
@use '@angular/material' as mat;
@use './path/to/m3-theme'
@include mat.core();
html {
  // Apply the light theme by default
  @include mat.core-theme(m3-theme.$light-theme);
  @include mat.button-theme(m3-theme.$light-theme);
}

Stable Deferrable Views

Deferrable views have always been in the talks and developers are quite excited about it. The reason behind this is excitement was enabling this will improve their app’s Core Web Vitals. Angular also presented that Bill.com shared that using @defer significantly reduced the bundle size of their app and that too by 50%. Developers are free to use deferrable views in their applications and libraries. 

Stable Built-in Control

In Angular version 17, along with deferrable views built-in control flow was also announced to perform at optimum. This new syntax was actively adapted by the Angular community and it is officially stable. In the process of improvement, the control flow’s type checking was updated along with the incorporation of ergonomic implicit variable aliasing. Some performance-related anti-patterns received set guardrails. 

Official Documentation Website

In the Angular 18 version, the official website for documentation in Angular is angular.dev. With the new look and feel, you can find tutorials in WebContainers, an intuitive playground with examples, and refreshed guides. 

Over the last one and a half years, Angular has relentlessly worked on making this website a success. All requests that will be made from Angular.io will now be directed to angular.dev.

4. Debugging and SSR Improvements 

In this version, major improvements have been made to ensure that developers can enhance the application building process and time and efforts are substantially saved. 

Server-Side Rendering

According to statistics, 76% of the Angular 17 apps that make use of prerendering or server-side rendering already use hydration. The lack of i18n support made it difficult for everyone to use it. Therefore, in the Angular 18 version, hydration for i18n blocks is available for developers in developer preview mode 

Debugging Experience

The Angular DevTools are updated to perceive Angular’s hydration process. Besides every component, you will find an icon presenting the component’s hydration status. An overlay mode can also be used to understand which component Angular hydrated on the page. Also, in the component explorer Angular DevTools will let you check the hydration errors in the application. 

5. Partial Hydration Strategy

Partial hydration is a method that permits you to hydrate your app serially after server-side rendering. The partial hydration was introduced at ng-conf and Google I/O. The incremental hydration in your application incorporates improved performance and loading limited JavaScript upfront. 

In the process, instead of rendering the @placeholder block on the server as it's happening in the present, you are able to have a mode where Angular will render the primary content of the @defer block on the server. Angular on the client side will download the associated JavaScript and hydrate a deferrable block. This is achieved only when the trigger conditions mentioned in the template are met. 

For example:  

@defer (render on server; on viewport) {
  <app-calendar/>
}

The block above will render the calendar component on the server. After it reaches the client, Angular will download the corresponding JavaScript and hydrate the calendar making it interactive once it enters the viewpoint. 

6. Control State Change Events

A property called events is now exposed by Angular forms from FormControl, FormGroup, and FormArray classes. This allows you to subscribe to a stream of events for this form control. You can analyze changes in value, pristine status, touch state, and more. 

const nameControl = new FormControl<string|null>('name', Validators.required);
nameControl.events.subscribe(event => {
  // process the individual events
});

7. Fallback Content for ng-content

One major issue that Angular has consistently heard is specifying default content for ng-content. Angular has heard and made sure change is done therefore it is now available. An example for this is:

@Component({
  selector: 'app-profile',
  template: `
    <ng-content select=".greeting">Hello </ng-content>
    <ng-content>Unknown user</ng-content>
  `,
})
export class Profile {}

Now you can use the component as follows:

<app-profile>
  <span class="greeting">Good morning </span>
</app-profile>

This will result in: 

<span class="greeting">Good morning </span>
Unknown user

8. Route Redirects as Functions

In the 18th version of Angular, redirectTo now takes a function that returns a string. This is enabled to become more flexible when dealing with redirects. If you want to redirect to a route that relies on some runtime state, you can implement an intricate logic in function:

const routes: Routes = [
  { path: "first-component", component: FirstComponent },
  {
    path: "old-user-page",
    redirectTo: ({ queryParams }) => {
      const errorHandler = inject(ErrorHandler);
      const userIdParam = queryParams['userId'];
      if (userIdParam !== undefined) {

        return `/user/${userIdParam}`;

      } else {

        errorHandler.handleError(new Error('Attempted navigation to user page without user ID.'));

        return `/not-found`;

      }

    },

  },

  { path: "user/:userId", component: OtherComponent },

];

Migration Automation to Application Builder

The application builder was announced in Angular version 17 and was incorporated by default for

No comments:

Post a Comment

SQL Commands - essentials

  SELECT # Retrieve data from the database FROM # Specify the table to select data from WHERE # Filter rows based on a condition AS # Rename...

Best for you