December 20, 2022
Last updated: September 8, 2023
Table of Contents
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.”
Angular 15 features bring forth a range of noteworthy updates that elevate the framework’s capabilities. The Angular 15 new features include:
A distinct comparison of the features found in Angular 14 and Angular 15 is given in the image below:
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.
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.
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:
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.
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.
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.
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:
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:
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.
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.
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.
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.
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”
]
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.
Node is not supported by Angular in version 15.Js, version 14.[15–19] or 16.[10-12]
In the Angular 15 new version, Angular no longer supports TypeScript versions older than 4.8.
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:
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.
In Angular v15, the title property is required on ActivatedRouteSnapshot.
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.
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.
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.
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
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.
Angular 15 was released on 16 November 2022.
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
Top 5 Frameworks and Tools to Build Progressive Web Apps
Progressive Web Apps have revolutionized the digital experience, offering users fast, engaging, and reliable apps directly through their browsers without the need for downloads. They combine the best of web and mobile applications, and building them requires robust front-end and back-end progressive web app frameworks and tools. Here’s a detailed guide to the top 5 […]
How to Build a Profitable Delivery Business Inspired by DoorDash Business Model
The DoorDash Business Model has revolutionized the way we think about on-demand delivery, becoming a household name in food delivery and beyond. From leveraging multiple revenue streams to creating a seamless experience for customers, restaurants, and delivery drivers, the DoorDash business model is a masterclass in operational excellence and consumer psychology. For aspiring entrepreneurs or […]
Top 10 Cloud Security Risks of 2024: Insights and Expert Solution
Did you know? By 2024, 94% of enterprises are projected to rely on cloud services, while the global cloud computing market will hit a staggering $1 trillion. With this monumental growth comes a parallel surge in threats. A recent report reveals that cyberattacks targeting cloud environments have increased by 27% year-on-year, with data breaches in […]
Are You Measuring E-Commerce Success the Right Way? Check These 7 Factors
Key Factors for Success in E-commerce – An Introduction Imagine setting up an e-commerce store, pouring your heart into every detail, and then wondering—how do you truly know it’s thriving? Success in the digital marketplace isn’t just about sales; it’s about creating a seamless experience that keeps your customers coming back. In today’s fast-paced digital […]
Best Cross Platform App Development Frameworks to Consider in 2024
The demand for cross-platform app development is skyrocketing in 2024, and it’s easy to see why. Instead of creating separate apps for iOS and Android, developers can now write code once and deploy it across multiple platforms with cross platform development frameworks. This not only saves time and money but also ensures a seamless user […]
5 Essential Steps to Build a Viral Casino Game
Casino games are more popular than ever, with millions of players logging in every day to try their luck on everything from slot machines to poker tables. But what does it take to create a successful casino game that not only entertains players but also stands out in a crowded market? In this guide, we’ll […]