Angular, the most popular open source front-end framework, has finally released another version update – Angular 15. Previously, Angular 14 introduced many new and exciting experimental features and permutations of coding best practices, but it looks like this new version – in Angular version 15, it’s all about gaining stability.
Finally, a new stable update that all of us technophiles and Angular community have been waiting for. This new update brings big exciting changes. So, let’s dive into the new world of Angular 15.
What new features did Angular 15 introduce?
Referring to other previous updates and the removal of the Angular legacy compiler, the Angular 15 update brings many new improvements – stability and extended support capabilities, which undoubtedly promise to improve the developer experience and performance.
1. Stable independent component API
In Angular 14, the Independent Components API was introduced for building Angular applications without definitions. In Angular 15, the Independent Components API has finally reached a level of stability after thorough performance observations and fixes. NgModules
The Angular developer community has ensured that with this newly implemented stability, individual components can work withHttpClient
Angular Elements and many other components work in sync.
Bootstrap applications in a single component using this independent API. Here’s how it’s 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);
use theimports
functions, you can even reference independent directives and pipelines.
You can now mark components, directives and pipes as ” standalone: true
” – now, there is no need to declare them into the NgModule, otherwise the Angular compiler will throw an error. Also, you can now writeimport: [module_name]
.
2. Enable the development of multi-routing applications
Angular 15 comes with a router-independent API to build multi-router applications. Here’s how to declare a root route:
export const appRoutes: Routes = [{
path: 'lazy',
loadChildren: () => import('./lazy/lazy.routes')
.then(routes => routes.lazyRoutes)
}];
Here, lazyRoutes is declared in the following way:
import {Routes} from '@angular/router';
import {LazyComponent} from './lazy.component';
export const lazyRoutes: Routes = [{path: '', component: LazyComponent}];
you canappRoutes
Register and use the tree-shakable API in the methodbootstrapApplication
call it!ProvideRouter
bootstrapApplication(AppComponent, {
providers: [
provideRouter(appRoutes)
]
});
Additionally, Angular Bundlers can now remove unused features at build time, which can reduce code file size by 11%.
3. Introduction to Directive Composition API
All developers love when their favorite framework offers first-class instruction reusability. In the GitHub community, many Angular developers were requesting this API, and finally, the team heard and made it possible.
So Angular v15 is finally infused with inspiration from feature requests on GitHub. It introduces the Directive Composition API, which boosts the usability of your code and takes it to another level. It allows developers to elevate host elements using directives and get the most out of Angular with the help of the resulting code reuse strategy. Also, all of this can be achieved with the help of the Angular compiler.
Notice:You can only use the Directive Composition API with standalone directives.
@Component({
selector: 'mat-menu',
hostDirectives: [HasColor, {
directive: CdkMenu,
inputs: ['cdkMenuDisabled: disabled'],
outputs: ['cdkMenuClosed: closed']
}]
})
class MatMenu {}
As you can see above, theMatMenu
This is made effective with the help of two hostDirectives:HasColor
andCdkMenu
.
Thanks to this enhancement,MatMenu
All attributes of these two directives can be reused. MatMenu can inherit the input, output and logic associated with the HasColor directive, and can only inherit fromCdkMenu
.
It might give you a sense of déjà vu for the concept of multiple inheritance. What sets Angular apart from other programming languages is name collision resolution, which only applies to user interface primitives.
4. Stable “NgOptimizedImage” image directive
ShouldNgOptimizedImage
directive was introduced in previous releases to easily adopt best practices for loading image performance. Finally, after a long period of observation by the developers, this directive has reached a stable form. Land’s End
A recent experiment with one app using this feature observed a 75% improvement in LCP (largest content paint) image loading.
before thisNgOptimizedImage
Many features and functions are also available, but Angular v15 update added more new and exciting features in image directive as follows:
- automatic
srcset
generate:It automatically generates the srcset, ensuring that images of the appropriate size are uploaded when requested – thereby reducing image download times.
- fill pattern [实验]:It removes the need to declare image dimensions and fill the image to its parent container. This mode is useful when you don’t know the image dimensions or you need to migrate CSS background-images to use the image directive.
But the question is, “How to use this standalone NgOptimizedImage directive?”
It can be used directly in your Angular components orNgModule
.
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 using this Angular image directive in a component, all you need to do is put the imagesrc
property is replaced withngSrc
while making sure to specify the priority attribute to optimize the speed of the LCP image.
5. Now you can reduce boilerplate code in Guards
Let’s understand this concept better with an example of defining a guard, validating details – whether the user is 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]
};
Here, in this program,LoginService
Contains the main logic, where the guard – only one trigger is called, which is isLoggedIn ()
. Despite such a clear structure, this code has a lot of boilerplate that must be reduced.
Thanks to Functional Router Guards, this code can be refactored to the code given below with the necessary boilerplate.
const route = {
path: 'admin',
canActivate: [() => inject(LoginService).isLoggedIn()]
};
The best thing about Functional Guards is that they are compostable. With its help, you can build factor-like functions that take a given configuration and return a guard or function that solves the problem.
6. Clearer and better stack traces
With the update to Angular v15, debugging Angular applications has been simplified and made clearer and more straightforward with stack traces. The Angular developer team made sure to implement a standard that tracks more of the development code than reveals which libraries it calls. This achievement makes the error messages could use some improvement.
Before using previous versions of Angular, when code was found, developers would often receive a one-line error message, leading them to a lengthy process of resolving the error.
Here is a snippet from the previous error indication:
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
The difficulty in understanding these error fragments is that:
- Error message input from 3rd party dependencies (Angular framework, zone.js and RxJS)
- There is no information on which user interaction encountered this error.
After a long-term collaboration with the Angular and Chrome DevTool teams, the community was able to integrate these third-party dependencies (with the help of node_modules, zone.js, etc.); thus, linked stack traces were possible.
Improvements to stack traces are described 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)
These error messages now provide information on where the error was encountered, so developers can go directly to that section of code and fix it immediately.
7. Stable MDC-based components
Due to concerns about the stability of Angular Material, the Angular development team worked hard to refactor its components based on Angular Material Design Components for web applications. Additionally, these components have been enhanced to provide better accessibility and adherence to the Angular Material Design specification.
Here, most of the refactoring work has been done in the DOM and CSS parts. With the new responsive update, some styles in the old Angular application need to be adjusted, especially in the case of CSS overriding the inner elements of the migrated components.
In the latest Angular v15, many components’ old implementations have been deprecated. So, to restore them, developers still have the option of “Legacy“Import.
For example, you canmat-button
Retrieve the old implementation by importing its legacy button module.
import {MatLegacyButtonModule} from '@angular/material/legacy-button';
8. CDK list box
CDK stands for Component Development Kit, which provides different behavioral primitives to help build UI components. In Angular v15, it got a new primitive called CDK Listbox that enables developers to customize the Listbox interactions drawn by the WAI-ARIA Listbox pattern as needed.
Here, behavioral interactions include keyboard interaction, bidi layout support, and focus management. No matter which of these you use, each directive has an associated ARIA role and its own host element.
9. Extended esbuild support
In the Angular 14 update, experimental support was enabled for esbuild – a faster javascript bundler that enables quicker builds by simplifying the pipeline.
Angular 15 isng build --watch
New experimental support for Sass, SVG templates, and file replacements.upgrade angular.json
The builder command is:
"builder": "@angular-devkit/build-angular:browser-esbuild"
10. Other Enhancements to Angular 15 Features
Below is a list of new enhancements and enablements in Angular 15 that may seem small but have a big impact.
- Router Now Auto-Unwarps Default Exports for Lazy Loading:It simplifies router functionality by adding more support and reducing more boilerplate. Here, for lazy loading, the router will look for the default export, and if successful, it will import its lazy file directly into the code.
- Automatic import of language support services – quick fixes:Now write Angular code with more confidence by taking full advantage of language services. You can use this feature to automatically import components and their fixes in templates that are not used in standalone components or NgModule.
- ImproveAngular Components: v15 of Angular Components covers a range of accessibility enhancements, including effective contrast, expanded touch target sizes, and improved ARIA semantics. Additionally, Angular components can customize their density using their API for a better theme customization experience.
It’s all about the new fixes and achievements enabled in Angular v15, but the question is, “How do you unlock these Angular 15 features?”
How to upgrade to Angular 15?
Before upgrading to Angular v15, you must understand Support Extensions, Deprecations and Deprecations – Breaking Changes to review and refactor your existing Angular builds.
- Angular v15 extends support for node.js 14.20.x, 16.13.x, and 18.10.x versions, and ends support for 14.[15-19].x and 16[10-12].x and other version support.
- Angular 15 now only supports TypeScript 4.8 or earlier.
- In the application project directory, run the command:
ng update @angular/core@15 @angular/cli@15
Harden your application with Angular v15 support. - @keyframes name format changed to ” “
@keyframes host-my-cmp_foo { ... }
- To comply with this breaking change:
- Change the component’s encapsulated view to None or ShadowDom.
- Define this rule in your global stylesheet
- Define this rule in your own code.
- To comply with this breaking change:
- Adding an explicit constructor to a class may trigger an error.
- In the tsconfig.json file,
enableIvy
The call has been removed, because in this update, Ivy is just a rendering engine. - Should
canParse
method has been removed so must now be used in the resolve methodanalyze
and parameters.hint
RouterOutlet
The component will only be instantiated after change detection is complete.- Should
DATE_PIPE_DEFAULT_TIMEZONE
functionality has been removed, so from now on, you need to use its replacementDATE_PIPE_DEFAULT_OPTIONS
to define the time zone. - Should
routerLinkWithHref
directive has been removed, so from now on you need to use theRouterLink
instructions to handle thehref
attribute element.
Well, there are other methods and directives that have been removed and updated with a new simplified syntax structure. Therefore, it is better to use the Angular v14 to v15 migration guide to ensure a smoother application migration.
Update Angular 14 to Angular 15 with the following command:
ng update @angular/cli @angular/core
Write below mentioned command in CLI to update your global Angular:
npm i -g @angular/cli
conclusion
The decision to launch Ivy in 2020 was the best decision because it brought a lot of improvements – NgModules being one of them. This improvement helps simplify the learning curve.
The Angular team is working on more improvements to the server-side rendering pipeline, and the next step is to improve code reusability to make Angular more efficient.
So, let’s upgrade to Angular v15 and wait for new exciting updates to get to know it.
#Angular #live #features #code #practice #deprecation #info #News Fast Delivery