Features of Angular 15

All the deprecations, refactorings, and new features in Angular 15 are here!

As the most popular open-source front-end framework, Angular is all set to rule the tech market with its latest release, known as Angular 15. Many interesting new experimental features and arrayed code best practises were introduced in Angular 14, but the latest version, Angular 15, is here to offer what was lacking in the previous version, which is stability.

For those who are already acquainted with Angular 14, the recent update has been a much-awaited one. So, without further ado, let us plunge into the world of the freshly released Angular 15.

The new features introduced into Angular 15

The Angular 15 update brings to the table many new refinements, including stability and extended supportability, both of which are motivated towards offering a first-class experience to developers.

Features of Angular 15

1. Reliable API for Use with Standalone Components

Introduced first in Angular 14, the standalone components API, which allows developers to create Angular applications without defining the NgModules, has been modified into a more stable component in the newly released Angular 15. This comes as a result of careful monitoring and adjustments to the previous design.

With this newfound reliability, independent components have established compatibility with HttpClient, Angular Elements, and others. The API can also be used individually for a quick and easy start. Underneath is an example that demonstrates this art.

import {bootstrapApplication} from '@angular/platform-browser';
import {ImageGridComponent} from'./image-grid';


@Component({
 standalone: true,
 selector: 'photo-gallery',
 imports: [ImageGridComponent],
 template: `
   … <image-grid [images]="imageList"></image-grid>
 `,
})
export class PhotoGalleryComponent {
 // component logic
}


bootstrapApplication(PhotoGalleryComponent);

The imports function allows users to utilise external directives and pipes. Standalone components, directives, and pipes can also be marked with the “standalone: true” attribute, eliminating the need to declare them into NgModule. It is also possible to import NgModule inside the standalone component itself by simply typing import: [module_name].

  1. Allows for the Creation of Multi-Route Applications

If you wish to create a multi-route application, Angular 15 includes a router standalone API. In order to help declare the primary route, here is an illustration-

export const appRoutes: Routes = [{
 path: 'lazy',
 loadChildren: () => import('./lazy/lazy.routes')
   .then(routes => routes.lazyRoutes)
}];

For declaration of lazyRoutes, the following process can be followed- 

import {Routes} from '@angular/router';


import {LazyComponent} from './lazy.component';


export const lazyRoutes: Routes = [{path: '', component: LazyComponent}];

The ProvideRouter API allows users to register appRoutes in the bootstrapApplication method.

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

To save on file space, Angular bundlers can filter out unused components during the compilation process, potentially shrinking the code base by 11%.

2. The Directive Composition Application Programming Interface (API)

An ideal framework is one that allows for the most effective directive reusability. As a response to the request by Angular developers in the GitHub forum, the team decided to implement the API into Angular v15.

With the new Directive Composition API, the code’s usability has been significantly improved. The latest version has given the green light to the use of directives to improve host elements, making this the best code reuse strategy available. An Angular compiler can also facilitate this process. However, it is important to keep in mind that the Directive Composition API can only be used with independently functioning directives.

@Component({
 selector: 'mat-menu',
 hostDirectives: [HasColor, {
   directive: CdkMenu,
   inputs: ['cdkMenuDisabled: disabled'],
   outputs: ['cdkMenuClosed: closed']
 }]
})
class MatMenu {}

Clearly, the two primary hostDirectives facilitating the proprr functioninh of MatMenu are HasColor and CdkMenu. The latest update prompts that MatMenu can use of all the features from these two essential hostDirectives. The inputs, outputs, and logic of the HasColor directive, as well as only the logic and input, can be inherited by MatMenu from CdkMenu.

The idea of multiple inheritance is manifested once again in this version. Moreover, unlike other programming languages, Angular’s focus is solely on resolving name conflicts among UI basics.

3. A reliable “NgOptimizedImage” Image Directive 

In the previous version, the NgOptimizedImage directive was introduced to make it simple to utilise best practises for speeding up the image loading process. But after a hectic testing process, this process has attained a great deal of stability in the latest Angular 15 version.

While NgOptimizedImage already comprised of a multitude of featires, Angular v15 brings some out of the box features to the image directive.

First, it generates srcset automatically. This  means that a requested image will be uploaded at the correct resolution and size, thereby speeding up the download process.

As an alternative to explicitly declaring image dimensions, the [experimental] Fill Mode has arrived. This mode fills the image to the size of its parent container. It comes in handy when one needs to change the CSS background image to use the image directive but is not sure of the exact dimensions. But a question that still remains unanswered is – how to use this NgOptimizedImage directive on its own? Well, the Angular 15 version allows you to implement it in your Angular app as a NgModule or component. Here is how you can do this-

import { NgOptimizedImage } from '@angular/common';


// Include it into the necessary NgModule
@NgModule({
 imports: [NgOptimizedImage],
})
class AppModule {}


// ... or a standalone Component
@Component({
 standalone: true
 imports: [NgOptimizedImage],
})
class MyStandaloneComponent {}

It is best to switch out the src attribute for ngSrc when using the aforesaid Angular image directive inside a component. Additionally, the priority attribute must be set to “fast” when working with LCP images.

4. Easy reduction of Boilerplate in Guards

The underlying example involves defining guards and verifying details, irrespective of whether the user has logged in or not.

 

@Injectable({ providedIn: 'root' })
export class MyGuardWithDependency implements CanActivate {
 constructor(private loginService: LoginService) {}


 canActivate() {
   return this.loginService.isLoggedIn();
 }
}


const route = {
 path: 'somePath',
 canActivate: [MyGuardWithDependency]
};

LoginService is the heart of this app. It is the only place where the program’s logic is executed and the guard is activated via the isLoggedIn trigger (). Despite the fact that the code is so clearly structured, this section of code contains far too many boilerplates and therefore, ought to be streamlined.

With the aid of Functional Router Guards, such a code can be refactored, as illustrated in the code underneath.

const route = {
 path: 'admin',
 canActivate: [() => inject(LoginService).isLoggedIn()]
};

The fact that Functional Guards break down in the compost is a huge plus point, allowing users to construct functions that act like factors. They take in an input configuration and output a guard that acts as a solution. 

5.Improved stack traces

Debugging Angular applications is now easier than ever before, thanks to the release of Angular v15. The version prioritised meeting a standard that would allow for the tracking of a program’s source code, as a result of which the error messages can be enhanced.

When users were faced with a bug in older versions of Angular, they would get one-liner error messages. This further led them to undertake  a lengthy process to fix the bug, a demonstration of which is offered below-

ERROR Error: Uncaught (in promise): Error
Error
   at app.component.ts:18:11
   at Generator.next (<anonymous>)
   at asyncGeneratorStep (asyncToGenerator.js:3:1)
   at _next (asyncToGenerator.js:25:1)
   at _ZoneDelegate.invoke (zone.js:372:26)
   at Object.onInvoke (core.mjs:26378:33)
   at _ZoneDelegate.invoke (zone.js:371:52)
   at Zone.run (zone.js:134:43)
   at zone.js:1275:36
   at _ZoneDelegate.invokeTask (zone.js:406:31)
   at resolvePromise (zone.js:1211:31)
   at zone.js:1118:17
   at zone.js:1134:33

These ERROR fragments were hard to decipher because the sources of the error messages were external, such as Angular framework, zone.js, and RxJS. Moreover, it is difficult to determine which user action may have triggered the bug.

Working with the Angular and Chrome DevTools teams, however, enabled the community  to integrate the necessary third-party dependencies via node modules, zone.js, etc. The changes made to the stack traces are shown here-

ERROR Error: Uncaught (in promise): Error
Error
   at app.component.ts:18:11
   at fetch (async) 
   at (anonymous) (app.component.ts:4)
   at request (app.component.ts:4)
   at (anonymous) (app.component.ts:17)
   at submit (app.component.ts:15)
   at AppComponent_click_3_listener (app.component.html:4)

These error messages direct users towards the problematic section of code, making it easier for developers to locate and fix the source of the error.

6. Stable MDC-based components

In order to ensure stability of web application, the Angular developer came up with a refactored set of components to match the Angular Material Design Components. Their conformity to the Angular Material Design Specifications ensures that the best version I brought before customers.

Refactoring efforts qete focused primarily on the DOM and CSS components. Compatibility issues were resolved by revising the older Angular applications’ styles, especially the CSS that overrides elements within the migrated components.

Although previously-used implementations of Angular components have been removed as of v15, developers can nevertheless use the “legacy” import to  etch them if needed.

As an example, the legacy button module of mat-button can be imported to revert to the previous implementation of mat-button.

The code reads: “import MatLegacyButtonModule from’ @angular/material/legacy-button;

7. Compact Disc Listbox (CDK)

The Component Development Kit, or CDK, provides a variety of behaviour primitives that can be used in the creation of user interface elements. CDK Listbox, added in Angular v15, allows developers to make adjustments to the WAI-ARIA Listbox pattern’s Listbox interactions as needed.

Keyboard interactions, support for bidirectional layouts, and attention management are all part of the behaviour interactions. For each directive, there is a set of ARIA roles that correspond to a specific set of host elements.

8. Enhanced esbuild backing

With the release of Angular 14, experimental support for esbuild was enabled. This is a faster javascript bundler that facilitates rapid development by streamlining of the pipeline.

The ng build – – watch support, Sass, SVG template, and file replacement are all new experimental features in Angular 15. In order to  update the angular.json builder, the following command is required-

“builder”: “@angular-devkit/build-angular:browser-esbuild”

9. Extra Improvements introduced in Angular 15

While many of the new features and improvements introduced in Angular 15 may seem subtle, it is undeniable that they cast an overarching shadow on the new version.

  • Router Now Auto-Unwarps Default Exports for Lazy Loading: The router’s capabilities have been streamlined through the addition of new enablement that automatically unwarps default exports for lazy loading. This helps to reduce boilerplate code even further. In case the router succeeds in spotting the default export, it immediately imports its lazy-file into the programme.
  • Instant Repair for Automatic Imports with Language Support: Using the language service effectively will allow you to write Angular code with greater assurance. When a component is not used in a standalone component or a NgModule, you can use this function to automatically import the component and its fixes into the template.
  • Enhanced Angular Components: Version 15 of the Angular components features numerous improvements to accessibility, such as higher contrast ratios, larger touch target sizes, and improved ARIA semantics. In addition, Angular components are capable of accommodating APIs to adjust their density, enabling them to have a better grip over theme customization.

How can you upgrade to Angular 15

It is imperative to refactor and review the current Angular build before upgrading to Angular v15, keeping in mind the path breaking changes introduced by the extension.

  • Angular v15 officially supports node.js versions 14.20.x, 16.13.x, and 18.10.x, while removing its support for older versions such as 14.[15-19].x and 16[10-12].x.
  • It does allow users to access a newer version of TypeScript than 4.8 with Angular 15. To ensure an application is compatible with Angular v15, the following command ought to be executed- ng update @angular/core@15 @angular/cli@15.
  • The name format for @keyframes has been updated to read “@keyframes host-my-cmp_foo {…}”

In order to adapt to this sudden shift:

  1. Set the encapsulation view of the component to None or ShadowDom.
  2. Establish this regulation in the system-wide templates
  3. Specify it as a requirement in your own code.
  • Errors may occur if a class’s function Object is made explicit. Since Ivy is now strictly a rendering engine, the enableIvy call has been removed from the tsconfig.json file.
  • With the elimination of the canParse method, the analyse and hint parameters in parse methods are now required.
  • Once RouterOutlet has finished its change detection, only then will the component be instantiated.
  • Since the DATE_PIPE_DEFAULT_TIMEZONE function is no longer available, thereby specifying the usage of DATE_PIPE_DEFAULT_OPTIONS.
  • No longer can users avail the routerLinkWithHref directive; instead, they must make use of the RouterLink directive when working with elements that have the href attribute. 

In favour of the more streamlined syntax of the latest version, many methods and directives have been removed. To ensure a more seamless application upgrade, using the Angular v14 to v15 migration guide is the best option.

If you are currently using Angular 14, you can upgrade to Angular 15 with this command:

ng update @angular/cli @angular/core

Type the following command into the command line interface to update Angular globally:

npm i -g @angular/cli

Conclusion

With the motivation of making the framework’s code more reusable, Angular’s dedicated development team has successfully refined the framework’s server-side rendering pipeline.

With the launch of Ivy in 2020 came numerous enhancements. One that stood out most is undoubtedly NgModules, which has greatly eased the learning process. Therefore, it is time to harness the potential of this new Angular version with the best developers in town. So, if you are looking forward to making the best use of this technology, don’t hesitate to get in touch with the industry’s most talented developers only at Sterling Technolabs.

custom software development
Scroll to Top