Angular 18

Angular 18 – Amazing Improvements and new features


Angular 18 was released on 22 May 2024! The new version offers several improvements and features that significantly improve how to build web applications with Angular. The release includes many stabilised APIs and introduces new features designed to simplify the use of the framework, streamline developer workflows and increase performance. This article will review the most essential features of Angular 18 and how they can transform and improve your web projects.

New control flow syntax

One of the most significant changes in Angular 18 is the new control flow syntax. This simplifies template management by integrating the control flow directly into Angular’s template compiler. Traditional structure directives like ngIf, ngFor, and ngSwitch can now be replaced with a more intuitive syntax.
Example:

<!- Previously ->
<div *ngIf="user">{{ user.name }}</div>

<!- Angular 18 ->
  @if(user) {
  <div>{{ user.name }}</div>
}

The same applies to ngSwitch and ngFor:
Example:

@switch (condition) {
@case (caseA) {
  caseA.
}
@case (caseB) {
  Case B.
}
@default {
  Default case.
  }
}

Advantages:
– Does not require a container element to hold the condition expression or each condition template
– Supports type checking of templates, including type restriction within each branch.

Example:

@for (item of items; track item.name) {
  <li>{{ item.name }}</li>
} @empty {
  <li>There are no items.</li>
}

Benefits:
– tracking expression (calculation of keys corresponding to item identities) is mandatory but has better ergonomics (it is enough to write an expression instead of creating the trackBy method)
– uses a new optimised algorithm to compute a minimal number of DOM operations to be performed in response to changes in a collection instead of Angular’s customisable diffing implementation (IterableDiffer)
– has support for @empty blocks.

Migration:
To migrate to this new syntax, use the provided schemas:

ng g @angular/core:control-flow

In addition, the new @for syntax, which replaces ngFor, improves the efficiency of list rendering by using a tracing key to avoid unnecessary DOM updates.

Improved defer syntax

The @defer syntax has also reached stability in Angular 18, enabling developers to conditionally load content with “lazy-loading”. This feature is handy for optimising load times and managing resources efficiently.

@defer(when user.name === 'Angular') {
  <app-angular-details />
} @placeholder {
  <div>Loading...</div>
} @loading(after: 100ms; minimum 1s) {
  <app-loader />
} @error {
  <app-error />
}

This syntax allows the specification of placeholders, loading states, and error handling directly in the template, offering a powerful way to handle asynchronous content.

Zoneless change detection with signals

Angular 18 introduces a groundbreaking but experimental feature: zoneless change detection with signals. Previously, Angular relied on Zone.js for change detection, which could introduce overhead. The new zoneless approach uses signals and lightweight observables that trigger change detection only when necessary, leading to significant performance improvements.

To use the new scheduler without Zone.js:

Example:

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

This change reduces dependencies and improves responsiveness in Angular applications.

Feature-based redirects in router

Routing in Angular becomes more dynamic with feature-based redirects. This feature allows developers to use functions for the redirectTo property, allowing more flexible and context-aware navigation.

Example:

const routes: Routes = [
  { path: '', redirectTo: (route: ActivatedRouteSnapshot) => {
    const queryParams = route.queryParams;
    return queryParams['mode'] === 'legacy' ? '/home-legacy' : '/home';
  }, pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'home-legacy', component: HomeLegacyComponent }
];

This functionality allows the retrieval of parameters and query parameters, providing more granular control over the navigation logic.

HttpClientModule is replaced by provideHttpClient

The HttpClientModule has been removed and replaced with the new provideHttpClient function. This change simplifies HTTP client setup and aligns with Angular’s move to standalone components.

Migration:

bootstrapApplication(AppComponent, {
  providers: [provideHttpClient()]
});

This update reduces module dependencies and simplifies application configuration.

Improved ng-content with fallback

Angular’s ng-content tag now supports default content, displayed when no content is provided. This improvement is beneficial for creating more robust and user-friendly components.

Example:

<button>
  <ng-content select=".icon">
    <i aria-hidden="true" class="material-icons">send</i>
  </ng-content>
  <ng-content>Default Button Text</ng-content>
</button>

This feature ensures that components display meaningful content, even if it is not explicitly provided.

Uniform form events

Angular 18 introduces a unified event property for form controls, which groups events like pristine, touched, status change, reset, and submit into a single observable. This enhancement simplifies the handling of form events and improves responsiveness.

Example:

@Component()
export class AppComponent {
  login = new FormControl(null);

  constructor() {
    this.login.events.subscribe(event => {
      if (event instanceof TouchedChangeEvent) {
        console.log(event.touched);
      } else if (event instanceof PristineChangeEvent) {
        console.log(event.pristine);
      } else if (event instanceof StatusChangeEvent) {
        console.log(event.status);
      } else if (event instanceof ValueChangeEvent) {
        console.log(event.value);
      } else if (event instanceof FormResetEvent) {
        console.log('Reset');
      } else if (event instanceof FormSubmitEvent) {
        console.log('Submit');
      }
    });
  }
}

This unified approach improves the developer experience by providing a consistent and easy way to handle form-related events.

Improvements in server-side rendering

Angular 18 introduces two essential improvements to server-side rendering (SSR): event replay and internationalisation (i18n) support. Event replay ensures that user interactions during hydration are captured and replayed when the application is fully interactive, improving the user experience. In addition, i18n support in SSR ensures seamless internationalisation, making it easier to build globally ready applications.

Enable SSR enhancements:

providers: [
  provideClientHydration(withReplayEvents()),
  provideClientHydration(withI18nSupport())
]

These features improve the stability and usability of SSR in Angular applications.

Improved developer tools

Angular 18 has improved developer tools, including better understanding and debugging capabilities. The Angular DevTools extension now offers enhanced performance metrics, dependency management, and status change tracking, making debugging and optimising applications easier.

Upgrade to Angular 18

To update from previous versions of Angular to Angular 18, you first need to check the compatibility of all dependencies and third-party packages. Next, update the Angular CLI and Angular Core, handle the deprecation of the HttpClientModule by switching to the provideHttpClient function, and migrate your code to the new control flow syntax. If you want, you can now implement zoneless change detection to improve performance.

Updating function-based redirects for more flexible routing and improving the fallback content components in ng-content is also essential. Improvements in server-side rendering should also be considered, including event playback and internationalisation. Make sure to use the latest version of TypeScript supported by Angular 18, thoroughly test your application after the update, and finally, build and deploy it when everything works correctly.

Summary Angular 18

Angular 18 is a comprehensive release that offers many new features and enhancements designed to improve the developer experience and application performance. These updates give developers the tools to build more efficient, robust, and user-friendly applications, from the new control flow and defer syntax to zoneless change detection and improved SSR. Upgrading to Angular 18 promises to streamline your development work and unlock new possibilities for your web projects.

By integrating these new features, developers can take full advantage of Angular 18’s capabilities, ensuring their applications are modern, scalable, and ready to meet the demands of today’s website users. Whether working on a new project or upgrading an existing one, Angular 18 offers the tools and enhancements needed to take your web application development to the next level.

Do you need help?

If you need help upgrading to Angular or help with any other migration, don’t hesitate to contact us at Gislen Software. We have the expertise and experience to ensure a smooth and efficient update process. Whether you face technical challenges or need strategic guidance, we are here to help you reach your goals. Contact us today to discuss how we can support your upgrade!

Was this article helpful?
YesNo

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>