Blog Details
blogAngular
What’s New in Angular 15? All New Features of Angular 15

A new stable update for Angular has been released. Angular has been a very amazing front-end open-source framework for web developers. The latest version is Angular 15 which comes with many useful features which community members were waiting for. In this article, we are going to see all the new features of Angular 15.

Features of Angular 15:

1. Directive Composition API

The directive composition API brings code reuse to some other level! This characteristic becomes stimulated via way of means of the maximum famous characteristic request on GitHub soliciting the capability to feature directives to several elements. The directive composition API permits builders to decorate host factors with directives and equips Angular with an effective code reuse strategy, that’s the most effective viable way for our compiler. The directive composition API most effectively works with standalone directives. Let’s see one example:

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

In the code snippet above we decorate MatMenu with directives: HasColor and CdkMenu. MatMenu reuses all of the inputs, outputs, and related good judgment with HasColor and bests the good judgment and the chosen inputs from CdkMenu. This method can also additionally remind you of more than one inheritance or trend in a few programming languages, with the distinction that we have a mechanism for the decision of call conflicts and it`s relevant to person interface primitives. This is one of the useful features of Angular 15.

2. Stable Standalone APIs

The standalone additives API was delivered in Angular 14 to construct Angular packages without defining the NgModules. In Angular 15, the standalone additives API sooner or later achieves its diploma of balance after thorough overall performance remarks and amendments. The Angular developer network has made certain that with this newly carried out balance, standalone additives can paint in sync with HttpClient, Angular Elements, and plenty of others. Use this standalone API to bootstrap a utility in an unmarried component. Here`s how it’s miles done:

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);

Using the imports function, you may even reference standalone directives and pipes. You can now mark components, directives, and pipes as “standalone: true” – now, no want to claim them into NgModule, else the Angular compiler will throw an error. Additionally, you may now import NgModule without delay within the standalone issue by writing import: [module_name]. This is one of the useful features of Angular 15.

3. HTTP with provideHttpClient

The new Angular 15 world, wherein modules are optional, stresses an evolution and adaption of HTTP support. With the assistance of provideHttpClient(), it`s feasible to provide the HttpClient. HTTP interceptors also are evolving and might now be described as functions. This is one of the useful features of Angular 15.

4. Functional Router Guard

Together with the tree-shakable standalone router APIs, we labored on lowering boilerplate in guards. Let`s examine an instance in which we outline the protection that verifies if the person is logged in:

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

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

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

LoginService implements maximum of common sense and withinside the shield we simplest invoke isLoggedIn(). Even though the shield is quite simple, we’ve got masses of boilerplate code. With the brand new purposeful router guards, you could refactor this code down to

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

We expressed the whole shield inside the shield declaration. Functional guards also are composable — you could create factory-like features that be given a configuration and go back to a shield or resolver function. You can locate an instance for jogging router guards serially on GitHub. This is one of the useful features of Angular 15.

5. Easy Lazy Loading

Angular 15 comes with a router standalone API to construct the multi-path application. Here`s how you could claim the basis path:

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

Here, lazyRoutes are declared withinside the following way:

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

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

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

It simplifies the router capabilities by including extra enablement to lessen even extra boilerplates. Here, for lazy loading, the router will search for the default export, and if it receives successful, it at once imports its lazy document into the code. This is one of the useful features of Angular 15.

6. Stable Image Directive

We introduced a developer preview of the Angular photograph directive that we evolved in collaboration with Chrome Aurora in v14.2.

Were excited about the percentage that it’s far now stable! Lands End experimented with this selection and discovered 75% development in LCP in a lighthouse lab test. The v15 release also includes a few new features for the image directive: Automatic srcset generation: the directive guarantees that a correctly sized photo is asked by producing the srcset characteristic for you. This can lessen download instances on your pix. Fill mode [experimental]: this mode reasons the photo to fill its determined container, putting off the requirement to claim the photos width and height. Its a hand device in case you dont understand the sizes of your pix or in case youd like to emigrate CSS history pix to apply the directive. You can use the standalone NgOptimizedImage directive directly in your component or NgModule:

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 {}

To use it inside a factor simply update the image`s src characteristic with ngSrc and ensure you specify the concern characteristic to your LCP images. This is one of the useful features of Angular 15.

7. Better Stack Traces

There were plenty of insights from annual developer surveys. Digging deeper into the struggles debugging enjoy builders face it is determined that mistaken messages should use a few improvements.

Debugging struggles for Angular builders The team partnered with Chrome DevTools to restore this! Let`s examine a pattern stack hint that you can get operating on an Angular app:

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

This snippet suffers from principal problems: There`s simplest one line similar to code that the developer has authored. Everything else is coming from third-birthday birthday celebration dependencies (Angular framework, Zone.js, RxJS) There are no statistics approximately what person interplay precipitated the error The Chrome DevTools crew created a mechanism to disregard scripts coming from node_modules with the aid of using annotating supply maps through the Angular CLI. We additionally collaborated on an async stack tagging API which allowed us to concatenate independent, scheduled async responsibilities right into an unmarried stack trace. Jia Li incorporated Zone.js with the async stack tagging API, which allowed us to offer connected stack lines. These adjustments dramatically enhance the stack lines builders see in Chrome DevTools:

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)

Here you may comply with the execution from the button press withinside the AppComponent in all of the manners to the error. You can examine greater approximately the enhancements here. This is one of the useful features of Angular 15.

8. Mistyped Banana in the Box

An intriguing feature that enhances the mistyped Banana in a Box fix has been added to Angular 15. In fact, in angular templates, banana in a box is merely a syntax for two-way data binding. You can shorten the syntax by using the banana in a box. For example,

<my-input [text]="val'' (textchange)="val=$event"></my-input>

You can write below instead of above

<my-input [(text)]="val"></my-input>

Coding can sometimes be written with the box inside and the parenthesis outside, as in: ([ ]). Since this kind of error causes angular to make mistakes, the most recent versions of angular will report such problems and provide a fix through language services.

9. Compatibility for MDC Components

In version 15, the Angular Material team made significant changes to the framework. In the past, Angular Material components implemented their own style based on the Material Design Guidelines. The components have been rewritten or reworked to use the official MDC (Material Design Components for Web) style since version 15. As a result, future versions of the Material Design specification can be implemented more quickly because there is now a common foundation. Precise Material will likewise profit from further developed openness of the MDC parts. This is one of the useful features of Angular 15.

10. Multi-Route Applications

The multi-route application can be built using Angular 15’s standalone router API. Declaring the root route can be done as follows:

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

Here, lazyRoutes are declared in the following way:

import {Routes} from '@angular/router';
import {LazyComponent} from './lazy.component';
export const lazyRoutes: Routes = [{path: '', component: LazyComponent}];

The appRoutes can be registered in the bootstrapApplication method and called through the tree-shakable ProvideRouter API!

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

Additionally, Angular Bundlers can now remove features that are not being used at the time of the build, which can reduce the size of the code file by 11%. This is one of the useful features of Angular 15.

11. Introduction to the Directive Composition API

All designers love it when their number one structure offers first-rate reusability of orders. Many Angular developers in the GitHub community requested this API, and the team finally granted their request. As a result, the GitHub feature request has been incorporated into Angular v15 for good. It has introduced the Directive Composition API, which significantly improves code usability. Developers can use directives to improve host elements and get the most out of Angular thanks to the ultimate code reuse strategy. Additionally, with the assistance of an Angular compiler, all of this is attainable.

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

As can be seen above, two hostDirectives help the MatMenu function properly: CdkMenu and HasColor MatMenu can reutilize all of these directives’ properties as a result of this improvement. Only the logic and input from CdkMenu can be inherited from MatMenu along with the HasColor directive’s inputs, outputs, and logic. It might make you think of Deja Vu when it comes to the idea of multiple inheritances. The resolution of name conflicts, which only applies to user interface primitives, sets Angular apart from other programming languages. This is one of the useful features of Angular 15.

12. Stable “NgOptimizedImage” Image Directive

In the previous version, the NgOptimizedImage directive was added to make it simple to use the best practices for loading image performance. This directive has finally reached a stable form after developers spent a considerable amount of time observing it. The LCP (Largest Contentful Paint) image loading has improved by 75% in the most recent Land’s End experiment with this feature for one application.

Already, this NgOptimizedImage was likewise offering many elements and functionalities, however Rakish v15 refreshes add all the more new thrilling highlights in the picture mandate, which are as per the following: Generating a srcset automatically: It generates srcset on its own, ensuring that an appropriately sized image is uploaded when requested, speeding up image downloads. The experimental fill mode: It fills an image to its parent container, removing the need to declare its dimensions. When you don’t know what the dimensions of the image are or need to move the CSS background image to use the image directive, this mode works pretty well. However, the question is, “How do I use this independent NgOptimizedImage directive?” It can be utilized directly in your NgModule or Angular component.

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 {}

Simply replace the image src attribute within a component with ngSrc to use this Angular image directive, making sure to specify the priority attribute to improve LCP image speed. This is one of the useful features of Angular 15.

13. Now You Can Reduce Boilerplate in Guards

Let’s look at an example of defining guards and verifying details – regardless of whether the user has logged in:

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

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

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

The main logic of this program is contained in LoginService, where the guard – only one trigger is called, isLoggedIn (). Despite its clear structure, this code segment must be reduced due to its numerous boilerplates. This code can be refactored into the given-below code with the necessary boilerplates thanks to Functional Router Guards.

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

The fact that Functional Guards can be composted is the best feature. You can construct factor-like functions that accept a given configuration and return a guard or function that resolves a problem with its assistance. This is one of the useful features of Angular 15.

14. Cleaner, Better Stack Traces

Using stack traces, debugging Angular applications has become simpler and cleaner with the Angular v15 update. The Angular team made it a priority to achieve a standard that allowed developers to trace more of the development code than just the libraries it calls. The error messages can now benefit from some enhancements thanks to this achievement. Developers used to receive one-liner error messages when they discovered a bug when working with earlier versions of Angular. This forced them to go through a lengthy process to fix the bug. The snippet for previous error indications is as follows:

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

Understanding these error snippets was difficult because Third-party dependencies (Angular framework, zone.js, and RxJS) were the source of the error message inputs. There is no indication of which user interaction encountered this bug. The community was able to integrate those third-party dependencies (with the assistance of node_modules, zone.js, and other tools) after extensive collaboration with the Angular and Chrome DevTool teams; and could, as a result, create linked stack traces. The following are examples of the enhancements to the stack traces:

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)

Now, these error messages indicate the location of the error, allowing developers to immediately address that code section and fix it. This is one of the useful features of Angular 15.

15. Stable MDC-based Components

Were satisfied to announce the refactoring of the Angular cloth additives primarily based totally on Material Design Components for Web (MDC) is now done! This alternate permits Angular to align even towards the Material Design specification, reuse code from primitives advanced through the Material Design team, and allow us to undertake Material three as soon as we finalize the fashion tokens. For most of the additives, weve been up to date on the patterns and the DOM shape, and for others, we rewrote from scratch. We stored a maximum of the TypeScript APIs and aspect/directive selectors for the brand-new additives equal to the antique implementation. We migrated hundreds of Google tasks which allowed us to make the outside migration route easy and file a complete listing of the adjustments in all of the additives. Due to the brand new DOM and CSS, you’ll probably discover that a few patterns for your utility want to be adjusted, especially in case your CSS is overriding patterns on inner factors on any of the migrated additives. The antique implementation of every new aspect is now deprecated, however nevertheless to be had from a “legacy” import. For example, you could import the antique mat-button implementation with the aid of using uploading the legacy button module.

import {MatLegacyButtonModule} from '@angular/material/legacy-button';

Visit the migration manual for greater information. We moved a number of the additives to apply layout tokens and CSS variables beneath neath the hood, to offer a clear direction for packages to undertake Material three thing styles. We resolved the 4th most upvoted issue — range selection support in the slider. To get a range input use:

<mat-slider>
<input matSliderStartThumb>
<input matSliderEndThumb>
</mat-slider>

Additionally, all additives now have an API to personalize density which resolved any other famous GitHub issue. You can now specify the default density throughout all your additives via way of means of customizing your theme:

@use '@angular/material' as mat;

$theme: mat.define-light-theme((
color: (
  primary: mat.define-palette(mat.$red-palette),
  accent: mat.define-palette(mat.$blue-palette),
),
typography: mat.define-typography-config(),
density: -2,
));

@include mat.all-component-themes($theme);

The new variations of the additives encompass a huge variety of accessibility improvements, which include higher evaluation ratios, accelerated contact goal sizes, and delicate ARIA semantics. This is one of the useful features of Angular 15.

16. CDK Listbox

The Component Dev Kit (CDK) gives a hard and fast of conduct primitives for constructing UI components. In v15 we brought every other primitive that you may customize to your use case — the CDK Listbox:

The @angular/CDK/Listbox module offers directives to assist create custom Listbox interactions primarily based totally on the WAI-ARIA Listbox pattern. By using @angular/CDK/Listbox you get all of the anticipated behaviors for an available experience, along with bidi format support, keyboard interaction, and cognizance management. All directives practice their related ARIA roles to their host element.

17. Extended esbuild support

In v14 we introduced the experimental guide for building in ng construct to permit quicker construct instances and simplify our pipeline. In v15 we have experimental Sass, SVG template, document replacement, and ng construct –watch support! Please provide build a strive through updating your developers angular.json from

"builder": "@angular-devkit/build-angular:browser"

to:

"builder": "@angular-devkit/build-angular:browser-esbuild"

If you come across any problems together with your manufacturing builds, allow us to recognize them by submitting a problem on GitHub.

18. Optimized CLI with a Bunch of Improvements

In the Angular CLI, we added a guide for standalone solid APIs. Now you may generate a brand new standalone issue through ng g issue –standalone. We`re additionally on an undertaking to simplify the output of ng new. As a primary step, we lessen the configuration with the aid of using eliminating test.ts, polyfills.ts, and environments. You can now specify your polyfills without delay in angular.json withinside the polyfills section:

"polyfills": [
"zone.js"
]

To reduce configuration overhead further, we now use .browserlist to allow you to define the target ECMAScript version. This is one of the useful features of Angular 15.

19. Router Unwraps Default Imports

To make the router less complicated and decrease boilerplate further, the router now auto-unwraps default exports while lazy loading. Let’s suppose you have the following LazyComponent:

@Component({
standalone: true,
template: '...'
})
export default class LazyComponent { ... }

Before this change, to lazy load a standalone component you had to:

{
path: 'lazy',
loadComponent: () => import('./lazy-file').then(m => m.LazyComponent),
}

Now the router will search for a default export and if it unearths it, use it automatically, which simplifies the direction announcement to:

{
path: 'lazy',
loadComponent: () => import('./lazy-file'),
}

20. Automatic Imports in Language Service

The language carrier now can mechanically import additives that youre the usage of in a template but havent delivered to a standalone issue or a NgModule. This is one of the useful features of Angular 15.

21. Dependency Injection

There are a few ways to make programming languages easier for developers to use. One such technique is Dependency Injection, which provides dependencies on another object to assist developers. The capability of one object to provide dependencies for another object is referred to as dependency injection. This is one of the useful features of Angular 15.

22. Community contribution highlights

Were thankful for the proportion that for the reason that launch of v14 we obtained contributions from over 210 humans throughout the framework, components, and CLI! In this section, Id like to focus on them. Provide an ability to configure default options for DatePipe This function through Matthias Weiß lets you globally alternate the default formatting configuration for DatePipe. Here`s an instance with the brand-new bootstrapApplication API:

bootstrapApplication(AppComponent, {
providers: [
  {
    provide: DATE_PIPE_DEFAULT_OPTIONS,
    useValue: { dateFormat: 'shortDate' }
  }
]
});

The configuration above will permit shortDate layout for all of the locations you operate DatePipe to your application. Add <link> preload tag for priority images during SSR To make certain precedence pictures are loaded as speedy as possible, Jay Bell brought a capability to the picture directive to encompass a tag for them while the use of Angular Universal. Theres no motion wanted in your give-up if youve already enabled the picture directive. If you have a special picture as precedence, the directive will robotically preload it. This is one of the useful features of Angular 15.

23. Deprecations

Major releases permit us to conform the framework closer to simplicity, higher developer experience, and alignment with the internet platform. After studying hundreds of tasks inside Google we observed a few not often used styles that in maximum instances are misused. As an end result, were deprecating providedIn: any’ is a choice with very restricted use other than a handful of esoteric instances in the framework. Were additionally deprecating providedIn: NgModule. It does now no longer have extensive usage, and in maximum instances is used incorrectly, in instances in which you have to pick providedIn: ‘root’. If you have to certainly scope vendors to a selected NgModule, use NgModule.vendors instead. With the evolving format in CSS, the group will prevent publishing new releases of @angular/flex-format. Well maintain presenting safety and browser compatibility fixes for the subsequent year. You can analyze greater approximately this withinside the first weblog published from our “Modern CSS” series. This is one of the useful features of Angular 15.


Excited about what’s coming up next!

The release of Ivy enabled a whole lot of enhancements throughout the board that you may locate already rolling out. Optional NgModules is an excellent example. It enables discount of the ideas novices want to cope with as a part of their important studying adventure and additionally helps superior capabilities which include directive composition API thru standalone directives. Next, were tackling enhancements in our server-aspect rendering pipeline and reactivity whilst bringing exceptional existence enhancements throughout the board! I cant wait to proportion with you what`s arising next! Till then let’s enjoy the new features of Angular 15!

All rights reserved by angulartemplates.com