What’s New In Angular 15: A Comprehensive Overview Of Features and Updates

author

Calibraint

Author

December 20, 2022

Last updated: September 8, 2023

angular 15 features

A Closer Look At Angular 15 Features: Noteworthy Updates and Additions

Angular 15 features mark a significant milestone in the evolution of the framework, bringing forth a compelling array of upgrades that firmly establish it as a leading contender among Angular versions. These remarkable enhancements directly address the challenges faced by developers using Angular 14, delivering solutions that greatly enhance stability, streamline API systems, introduce the convenience of single-file components, and extend support for ESbuild. Thus, the various Angular versions play a crucial role in the framework’s evolution and the overall development landscape. 

“According to Minko Gechev (Google’s Head of Product for Angular), updating to the new features of Angular 15 stands out as one of the most significant and exciting releases of 2022.”

What Is New In Angular 15?

Angular 15 New Features In A Nutshell

Angular 15 features bring forth a range of noteworthy updates that elevate the framework’s capabilities. The Angular 15 new features include: 

  • Angular standalone components are now in the stable API surface
  • The new router standalone APIs can be used to create multi-route applications 
  • Directive composition API
  • Stable NgOptimizedImage directive
  • Functional route guards
  • Enhanced stack traces
  • CLI Improvements

The Basic Difference Between Angular 14 & Angular 15 Features

A distinct comparison of the features found in Angular 14 and Angular 15 is given in the image below:

Angular 14 Vs. Angular 15 Differences

A Deeper Look At Angular 15 New Features: Recent Updates And Upgrades

1. Angular Standalone Components Are Now In The Stable API Surface

Angular 15, the angular latest version update, is built upon the foundation laid by version 14, which introduced a set of standalone APIs that allowed developers to build applications without relying on NgModules. In the angular latest version update, these APIs have transitioned from being a developer preview to being part of the stable API surface. Moving forward, these APIs will continue to evolve gradually, following semantic versioning principles.

To ensure the readiness of standalone APIs for production use, extensive compatibility testing has been conducted with various Angular features. As a result, standalone components seamlessly integrate with essential components such as HttpClient, Angular Elements, and the router. This integration empowers developers to effectively utilize standalone components throughout their Angular applications.

Yet another significant advantage of the standalone APIs is the ability to bootstrap an application using just a single component. This streamlined approach simplifies the initialization process and promotes modularity within the application’s architecture. By leveraging standalone components, developers can optimize their application’s structure and achieve enhanced performance.

Stable Standalone APIs In Angular 15

The new router standalone APIs can be used to create multi-route applications! 

You can use the following to declare the root route:

export const listRoutes: Routes = [{
path: ‘list’,
loadChildren: () => import(‘./list/list.routes’)
.then(routes => routes.listRoutes)
}];

Where listRoutes are declared in
import {Routes} from ‘@angular/router’;
import {ListComponent} from ‘./list.component’;
export const listRoutes: Routes = [{path: ”, component: ListComponent}];

Lastly, add the app to the bootstrapApplication call.
bootstrapApplication(AppComponent, {
providers: [
provideRouter(appRoutes)
]
});

The use of the provideRouter API offers the additional advantage of being tree-shakable, enabling bundlers to eliminate redundant router functionalities during the building process. As a result, the size of the router code in the application bundle is significantly reduced.  To be specific the Angular team achieved an impressive 11% reduction in the size of the router code. This optimization has greatly improved the overall performance of the application, leading to faster loading time due to the reduction in bundle sizes.

2. Directive Composition API

The directive composition API in the new features of Angular 15 empowers developers to augment host elements with directives, providing a robust code reuse strategy and this feature is made accessible through the compiler. It’s important to note that the directive composition API is specifically designed for solo directives. By leveraging this API, developers can enhance code modularity and achieve reusability by combining multiple directives to enhance the functionality and behaviour of host elements.

Let’s take a look at a quick example:

Directive Composition API In Angular 15

In the provided code snippet, we can enhance the functionality of MatMenu by applying two directives: HasColor and CdkMenu. By using these directives, MatMenu can reuse all the inputs, outputs, and associated logic from HasColor, while selectively incorporating the logic and chosen inputs from CdkMenu.

This approach bears a resemblance to multiple inheritance or traits in certain programming languages. However, it is important to note that the Angular mechanism provides a resolution strategy for conflicts in naming and is specifically designed for user interface primitives.

3. Stable NgOptimizedImage Directive 

By integrating the NgOptimizedImage directive into your Angular component or NgModule, you can significantly reduce the time it takes to download images in your application. This directive simplifies the implementation of performance optimization techniques for image loading.

The NgOptimizedImage directive in Angular 15 changes provides various features to prioritize the loading of the Largest Contentful Paint (LCP) image. It achieves this by automatically setting the fetch priority attribute on the <img> tag, enabling lazy loading for other images by default, ensuring the inclusion of a preconnect link tag in the document head, generating an src set attribute, and producing a preload hint in the case of server-side rendering (SSR).

In addition, NgOptimizedImage in Angular 15 changes encompasses a range of image best practices that go beyond LCP optimization. Here are some of these practices:

1. Responsive Image Handling: The directive automatically generates responsive src set attributes based on device capabilities. This ensures that the appropriate image version is loaded according to the screen size and resolution, enhancing the user experience across various devices.

2. WebP Format Support: NgOptimizedImage seamlessly provides fallback support for the WebP image format. WebP offers superior compression and performance advantages for browsers that support it, resulting in faster image loading and improved efficiency.

3. Lazy Loading: The directive implements lazy loading for images that are not immediately visible in the viewport. By deferring the loading of these images until they are needed, initial page load times are improved, leading to a faster and smoother user experience. This approach also helps conserve bandwidth, particularly for users with limited data plans.

4. Image Compression: NgOptimizedImage incorporates image compression techniques to reduce file sizes without significant loss in visual quality. By optimizing the images, download time is reduced, resulting in faster loading pages and improved overall performance.

By embracing the NgOptimizedImage directive and adhering to these recommended image best practices, you can significantly boost the loading speed and overall performance of images within your Angular application.

  • Using image CDN URLs to apply image optimizations
  • Preventing layout shift by requiring width and height
  • Warning if width or height has been set incorrectly
  • Warning if the image will be visually distorted when rendered

Having said that, let us look at the steps involved: 

Step 1: Import NgOptimizedImage

import { NgOptimizedImage } from ‘@angular/common’;

The directive is defined as a standalone directive. Thus the components should import it directly.

Step 2: (Optional) Set up a Loader

An image loader is not required in order to use NgOptimizedImage. However using one with an image CDN enables powerful performance features, including automatic src sets for your images.

Step 3: Enable the directive

In order to use the NgOptimizedImage directive, change the src attribute of your image to ngSrc.

<img ngSrc=”calibraint.jpg”>

If you are utilizing a built-in third-party loader, it is important to exclude the base URL path from the src attribute. The loader will automatically prepend the base URL path, so there is no need to include it explicitly.

Step 4: Mark images as a priority

Always mark the LCP image on your page as a priority to prioritize its loading.

<img ngSrc=”calibraint.jpg” width=”400″ height=”200″ priority>

Marking an image as priority applies the following optimizations:

Sets fetch priority=high (read more about priority hints here)
Sets loading=eager (read more about native lazy loading here)

This automatically generates a preload link element if rendered on the server.

During development, Angular will display a warning if the Largest Contentful Paint (LCP) element, such as an image, lacks the priority attribute. The LCP element of a page can differ based on various factors, including the user’s screen dimensions. Therefore, a page might contain multiple images that should be designated as priority elements.

Step 5: Include Height and Width

To avoid image-related layout shifts, it is necessary to provide explicit height and width values for your images when using NgOptimizedImage. By specifying the height and width attributes, you can ensure that the space required for the image is reserved in the layout, preventing unexpected shifts in content while loading the image. You can specify the height and width for your image, as follows:

<img ngSrc=”calibraint.jpg” width=”400″ height=”200″>

The width and height attributes for responsive images (images that you’ve configured to expand and contract in relation to the viewport) should match the intrinsic size of the image file.

The width and height attributes for fixed-size pictures should accurately reflect the rendered size of the image. These characteristics’ aspect ratios must always coincide with the image’s natural aspect ratio.

Note: Consider using “fill mode” to inherit the size of the parent container if you are unsure about the size of your images.

4. Functional Router Guards

Along with the new features in Angular 15, significant efforts have been made to reduce boilerplate code in guards, particularly in conjunction with the tree-shakable standalone router APIs. Let’s examine an example that demonstrates the definition of a guard responsible for verifying if the user is logged in:

Functional Router Guards In Angular 15 Features

LoginService implements most of the logic and in the guard, one has to only invoke isLoggedIn(). Even though the guard is pretty simple, one will have a lot of boilerplate code.

With the new functional router guards, you can refactor this code down to:

Angular 15 Functional Router Guards

In Angular, there is an approach where the entire logic of a guard can be encapsulated within the guard declaration itself. This allows for a more concise and self-contained implementation of guards. Additionally, functional guards offer the flexibility of composability. Developers can create factory-like functions that accept a configuration and return a guard or resolver function, making it easier to customize and reuse guards in different scenarios.

5. Automatic Imports In Language Service

The Angular 15 new features now offer the capability to automatically import components that are used in templates but haven’t been explicitly added to standalone components or NgModules. This feature simplifies the development process by automatically resolving and importing the necessary components, reducing the need for manual imports.

Angular 15 Automatic Imports In Language Service

In the template, an error will be displayed when using the stand-alone selector without importing the corresponding component. However, the Angular language service provides a quick fix option that automatically imports the required component into the import section. After applying the quick fix, the code will be updated to include the import statement for the component, thereby resolving the error.

Automatic Imports In Language Service In Angular 15

6. Better Stack Traces

Along with the new features in Angular 15, significant improvements have been made to enhance the debugging capabilities of Angular applications. Through collaboration with Google Chrome developers, Angular has refined the presentation of stack traces, resulting in more streamlined and informative outputs.

The updated stack traces prioritize displaying more of the application-specific code while minimizing the inclusion of underlying libraries and frameworks that Angular relies on. This refinement allows developers to focus on their own code and reduces the clutter caused by lower-level library calls in the stack trace.

By providing cleaner and more focused stack traces, debugging becomes more efficient and less time-consuming. Developers can swiftly pinpoint the source of errors or exceptions and gain a better understanding of their application’s flow. Angular 15 features significantly improves the debugging experience for Angular applications by providing clearer context and minimizing irrelevant information.

7. CLI improvements

In the Angular CLI, the team has introduced support for standalone stable APIs. A new standalone component can now be created using

ng g component –standalone.

The Angular team is actively working to simplify the output of the ng new command. As an initial step, the configuration has been streamlined by removing the test.ts, polyfills.ts, and environments files. Instead, you can now specify your desired polyfills directly in the angular.json file, within the polyfills section. This change aims to make the project structure more straightforward and easier to manage.

“polyfills”: [
“zone.js”
]

Changes To Be Known In Angular 15 Features To Ensure Compatibility

With Angular 15 features, certain aspects behave differently, which may necessitate reviewing and refactoring specific sections of your Angular application. It is important to be aware of these changes to ensure compatibility and optimal functioning. 

1. Angular v15 supports node.js versions: 14.20, 16.13 and 18.10

Node is not supported by Angular in version 15.Js, version 14.[15–19] or 16.[10-12]

2. Angular v15 supports TypeScript version 4.8 or later

In the Angular 15 new version, Angular no longer supports TypeScript versions older than 4.8. 

3. @keyframes name format changes

The component’s scope name appears before the @keyframes prefix in version 15. 

For example, in a component definition whose scope name is our-cmp, a @keyframes rule with a name in v14 of:
@keyframes foo { … }
becomes in v15:
@keyframes our-cmp_foo { … }

This change can break any TypeScript or JavaScript code that uses the names of @keyframes rules. 

To accommodate this breaking change, you should ensure that:

  • View encapsulation for the component is changed to ShadowDom or None.
  • In global stylesheets like styles.css, define @keyframes rules.
  • Create your own @keyframes rules in the code.

4. Compilation Problems May Be Reported By Invalid Constructors For Dependency Injection

The latest Angular 15 features introduce a change related to constructor inheritance in classes. The compiler now identifies potential issues that may arise when using an inherited constructor for dependency injection in cases where a class inherits its constructor from a base class.

Previously, the runtime behavior could be unpredictable if the base class lacked the required Angular decorators like @Injectable() or @Directive(), or if the constructor included parameters without corresponding tokens (e.g., primitive types like string). In such cases, a class could still be created even if none of the constructor parameters were fulfilled.

However, in v15, these scenarios are now flagged as compilation errors. This modification facilitates the detection of these problems during the development phase, preventing potential issues from occurring in the runtime.

There are two suggested methods for fixing these reported errors:

1. Decorate the base class: If the base class lacks essential Angular decorators like @Injectable() or @Directive(), you can add the missing decorator. This ensures that the required metadata is available for accurate dependency injection.

2. Add an explicit constructor: If the reported issue occurs in a class that inherits its constructor, you can add an explicit constructor to that class. This allows you to provide the necessary tokens for dependency injection or perform any additional initialization logic that may be required.

By taking these steps, you can ensure that dependency injection functions correctly in your Angular application and that constructor inheritance in your classes behaves as intended.

5. On ActivatedRouteSnapshot, The Title Property Is Necessary

In Angular v15, the title property is required on ActivatedRouteSnapshot. 

6. RouterOutlet Instantiates The Component After Change Detection

In earlier versions of Angular, when using RouterOutlet for navigation, the component would be instantiated immediately. However, in the latest Angular 15 features, this behavior has changed. Now, the component is not instantiated until the change detection process is completed.

This change can have an impact on tests that implicitly trigger change detection after router navigation. If your tests rely on the immediate availability of the component, they may need to be modified to accommodate the new timing.

Furthermore, this change in component instantiation timing can also affect production code that depends on the precise moment of component availability. For example, if your component’s constructor uses the router and relies on getCurrentNavigation(), its behavior may be affected by the altered behavior in v15.

To adapt to these changes, it is recommended to update your tests to include appropriate change detection triggering after router navigation. Additionally, if your production code relies on the timing of component instantiation, you may need to adjust the logic to align with the updated behavior in v15.

By considering these changes and making the necessary adjustments, you can ensure that your tests and production code continue to function as intended and account for the modifications in component instantiation timing introduced in Angular 15 features.

7. relativeLinkResolution Is Not Configurable In The Router

Starting from Angular version 15, the relativeLinkResolution feature in the Router is not programmatically configurable. In previous versions, users had the option to opt-out of a bug fix by choosing not to apply it. However, in v15, this flexibility is no longer available, and the relativeLinkResolution behavior cannot be customized.

Concluding Lines

The latest release of Angular, version 15, demonstrates the remarkable dedication of the Angular Team at Google to cater to the needs and aspirations of developers and the wider community. This version showcases significant advancements and carefully considers the valuable feedback received since the previous release.

For product owners planning to leverage the power of Angular in their upcoming projects, it is highly recommended to hire skilled Angular developers from the best technology consulting company who can harness the immense potential that Angular offers. The latest Angular 15 features and updates provide stability, standalone APIs, and a robust CLI capable of generating applications without modules.

Angular 15 features also focus on enhancing stability, refining the developer experience, and boosting performance, among various other updates. The Angular Team’s commitment to continually improving the framework ensures that developers can expect even more anticipated and unexpected improvements in the future.

Thus, with Angular 15 features, developers can embark on a promising journey of web application development. So don’t hesitate any longer and get ready right away to embrace the new possibilities offered by Angular 15 features. 

Frequently Asked Questions

1. What Are The Recent Angular 15 Updates? 

The top Angular 15 updates are:

1. Stable Standalone APIs

2. Directive composition API

3. Stable NgOptimizedImage Directive

4. Improved Stack Traces for Debugging

5. Enhanced Experimental ESbuild Support

2. What Is The Difference Between Angular 14 and 15?

Angular 15 is built upon the foundation laid by Angular 14, introducing a host of updates and enhanced features that contribute to a more stable and refined framework. Notably, Angular 15 features incorporates a newer and improved API system, offering developers a more efficient and advanced set of tools for building robust applications. 

3. When Was Angular 15 Released?

Angular 15 was released on 16 November 2022.

4. What Version Of TypeScript Is Angular 15?

Angular 15 features exclusively supports TypeScript versions up to 4.8, including earlier versions. To ensure compatibility with Angular v15, navigate to your application’s project directory and execute the following command: ng update @angular/core@15 @angular/cli@15. 

Reference: Angular.io

Related Articles

field image

Forget “For Sale” signs outside houses and endless cold calls. The future of real estate lead generation is undeniably digital. In today’s world, potential buyers begin their home search online, making a wide web presence crucial for any agent looking to maximize property sales.  In this blog post, we will explore how these innovative tools […]

author-image

Calibraint

Author

04 Apr 2024

field image

An Introduction To Cost Reduction In Inventory Management Do you ever feel like you’re constantly playing inventory whack-a-mole? Stockouts costing you sales? Or maybe you’re drowning in a sea of unused products eating away at your profits? Inefficient inventory management can be a major drain on your business resources. But what if there was a […]

author-image

Haritha

29 Mar 2024

field image

What If I Told You That A Website Is Already An App? There is a saying “If you can’t convince them, confuse them”! This is exactly what Web Apps and Mobile Apps do with us. So if “Web App vs Mobile App: Which one should I choose” is your question, then this blog has all […]

author-image

Calibraint

Author

13 Feb 2024

field image

PWAs are no longer a futuristic fantasy; they’re a present-day reality, transforming how businesses connect with their audience. Stats back this up as several reports suggest increased conversions and user engagement with PWAs over traditional websites. And let’s not forget the search engine love – PWAs get indexed and appear in app store listings, expanding […]

author-image

Calibraint

Author

10 Feb 2024

field image

WE HAVE DETECTED AN UNSAFE LINK!!!! Ever felt that gut-wrenching ‘ohhh noo’ moment when you realize your website is under attack? In 2024, the web is a wild west of cyber threats, and your website might be the next frontier.  Picture this: Everything you’ve built vanished in the blink of a malicious code. But fear […]

author-image

Haritha

25 Jan 2024

field image

Building a web application or platform with a seamless user experience takes two crucial ingredients: a brilliant vision and a talented full stack developer to bring it to life. Before you embark on your search to hire full stack developers, let’s take a moment to set the stage. This first step requires introspection, clarity, and […]

author-image

Calibraint

Author

19 Jan 2024

Let's Start A Conversation

Table of Contents