Angular 15 New Features | Angular v15 is now available!

After the releasing Angular 14 this year, now Angular 15 is released this month (November 2022) with a couple of features including performance improvement. Previously we saw a new feature added to Angular 14. The released Angular 15 version is a stable version.
In this article, we are going to discuss the new feature added to Angular 15.



Angular 15 new features

  1. Stable Standalone Components API
  2. Standalone APIs to create a multi-route application
  3. Directive composition API
  4.  Image Directive (NgOptimizedImage) is now Stable
  5. Functional router guards
  6. The router unwraps default imports
  7. Better stack traces
  8. Stable MDC-based Components
  9. CDK Listbox
  10. Extended esbuild support



In this article, we are going to discuss the above Topics.

 
1.       Stable Standalone Components API

We see in Angular 14, the standalone APIs introduced to create angular applications without using the NgModules.
In Angular v15, standalone APIs are now stable after a couple of observation-like performances by the angular team.
In Angular v15, the Angular developer team achieved stability so now standalone components can work in sync with HttpClient, routers, Angular Elements, and more.
 
Standalone API allows us to bootstrap an application in a single component.
Here’s the code to do this:



import {bootstrapApplication} from '@angular/platform-browser';
import { StudentNameComponent } from './StudentName/StudentName.component';
@Component({
  standalone: true,
  selector: 'student-Names',
  imports: [StudentNameComponent],
  template: `
    … <student-grid [stdNames]="stdNamesList"></student-grid>
  `,
})
export class Angular15AppComponent {
  // component logic
}
bootstrapApplication(Angular15AppComponent);


Using the imports function, we can also reference standalone directives and pipes.
 
We can now mark components, pipes, and directives as “standalone: true” – now, no need to declare them into NgModule, else the Angular compiler will throw an error.
We can now import NgModule directly inside the standalone component by using import: [module_name].



2. Standalone APIs to create a multi-route application
Now we can build the multi-route application using the new router standalone APIs.

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

Where lazyRoutes are declared in

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

and now, register the appRoutes in the bootstrapApplication call 

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


here  provideRouter API is the tree-shakable.
At the build time, Bundlers can remove unused features from the router that reduce around 11% of code bundle size.

3. Directive composition API


This feature is implemented because of a feature request created on GitHub for adding the functionality to add directives to the host element.
it helps us in code reusability and it also allows developers to increase host elements with the directives and build the angular application with the help of code reusability, and it is possible with the help of the angular compiler.
The directive composition APIs only work with the standalone directives

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


in the above code, we enhance MatMenu with the 2 directives called HasColor and CdkMenu.
MatMenu helps us to reuse all the inputs, outputs, and related logic with HasColor and only logic and the selected input from the CdkMenu.



4. Image Directive (NgOptimizedImage) is now Stable


The NgOptimizedImage was introduced in V14.2, which helps us to easily adapt for loading image performance.
Now in Angular v15, it is stable.  Land’s End worked with this feature and introduced a 75% improvement in LCP (Largest Contentful Paint) in a lighthouse lab test for image loading.




previous version NgOptimizedImage having many features and functionalities, 
Now Angular v15 updates added a couple of new features in the image directive.

  1. Automatic srcset Generation: this directory automatically generates the srcset, which helps us to upload an appropriately sized image whenever requested. This reduces the download time of an image.

  1. Fill Mode [experimental]: this mode removes the need for declaring image dimensions and fills the image to its parent container. This mode is useful when we don't know the image dimensions we need to migrate the CSS background image to make use of this directive.

with the use of NgOptimizedImage directive, We can directly use NgOptimizedImage directive in angular 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 {}

when we are working with NgOptimizedImage  directive within a component, then we need to replace the image src attribute with the ngSrc.

5. Functional router guards
With the help of tree-shakable standalone router APIs, we work on reducing the boilerplate in the guards.

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

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

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

here LoginService implements most of the logic and in the guard we only invoke isLoggedIn(). Even though the guard is pretty simple, we have lots of boilerplate code.
Now with the new functional router guards, we can refactor the code like below.


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

we created the entire guard in the guard declaration. The best thing about Functional Guards is that they are compostable.
 You can find an example of running router guards serially on GitHub.

6. The router unwraps default imports

To make the router simpler and reduce boilerplate further, the router now auto-unwraps default exports when 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 look for a default export and if it finds it, use it automatically, which simplifies the route declaration to:


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


7. Better stack traces


In Angular v15, now we can easily trace the code, it helps us when we face any error, so using stack trace we can find the place where the error is coming.


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

So angular v15 developer team introduce this feature to trace more of a development code than showing libraries it calls.
In the previous version we have to give a lot of time to trace the error, but in v15 is easy to trace.
Below is the snippet for previous error indications:

 

  1. above error message coming from third-party dependencies (Angular framework, zone.js, and RxJS)
  2. we can see here no information was given about which user interaction encountered this bug. 

Now in Angular v15 stack trace will be like below

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)

8. Stable MDC-based Components

Previously it was hard to reflector component-based angular material, but now it is possible by using MDC (Material design component for web)

In v15, majorly the refactoring work has been done in the DOM and CSS parts. Following the new update on responsiveness, there will be some styles in the old Angular applications that need adjustments, especially in the case of CSS overriding internal elements of the migrated components.

In v15, the old implementation of each new component is now deprecated, but still available from a “legacy” import

For example, we can retrieve the old mat-button implementation by importing its legacy button module.


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




More improvements in components

In angular v15 couple of the user, observations are implemented  — range selection support in the slider.

To get a range input use

<mat-slider>

  <input matSliderStartThumb>

  <input matSliderEndThumb>

</mat-slider>

Additionally, all components now have an API to customize density which resolved another popular GitHub issue.

You can now specify the default density across all of your components by 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 versions of the components include a wide range of accessibility improvements, including better contrast ratios, increased touch target sizes, and refined ARIA semantics.

 

9. CDK Listbox

CDK stands for Component Dev Kit gives different behavior primitives and helps in creating UI components. 

In the Angular v15, a new primitive called CDK Listbox was added, which helps developers to customize Listbox interactions drawn up by the WAI-ARIA Listbox pattern based on requirements..

CDK Listbox

Here, the behavioral interactions include keyboard interactions, bidi layout support, and focus management. No matter which one of them you use, each directive comes up with associated ARIA roles with respective host elements.

10. Extended esbuild support




In v14 having support for esbuild in ng build which enables faster build times and simplifies the pipeline.

Now v15 has experimental Sass, SVG template, file replacement, and ng build --watchsupport! 

Update esbuild in  angular.json 

From

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

to:

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



 

 



------------------------------

Share this

Related Posts

Previous
Next Post »