Latest Features of Angular.js

The latest version of Angular was slated to release in March-April 2019. But, it eventually happened in 2019. Yes, we are talking about Angular 8 – the latest version of Angular.js.
However, Angular 7.0 got supported until April 2022. So, it becomes imperative for organizations to explore the new features incorporated in Angular 8 and decide on embracing Angular 8 or not, upgrading from Angular 7.0.
What are the New Features of Angular 8.0?
Differential Loading of JavaScript
Differential loading enables the browsers to select optimized or legacy bundles according to their capabilities and then automatically loads the
correct one. The users receive the bundles required by them.
In the latest version, Angular serves different browsers with different bundles, and this is by default. The CLI extensions generate different bundles for old legacy (ES5) browsers and modern JavaScript (ES2015+) browsers.
Moreover, it enhances the loading speed and the time to interactive (TTI) for a modern browser. The speed of applications and building a process takes place by using polyfills or modern syntax. Moreover, different loading also helps in saving 7 – 20 % of bundle size on average.
Differential loading in Angular 8.0 forms a part of Manfred Steyer and his project ngx-build-modern. The entire bundling is done with ng build command and the -prod extension – without requiring special actions.
Opt-in Usage Sharing
It acts as an addition to Angular CLI that aligns Angular 8 with community needs. Angular needs to keep a tab on how developers use the platform and what are the improvements required. It is done with the information on the command used and builds speed. You can share telemetry on CLI usage with your developer team.
Angular emphasizes consent on data sharing, unlike other platforms that collect data by default on an opt-out basis. It stops when you command them not to. Others don’t even allow them to ask them to share telemetry.
Improved Web Worker Bundling
With CPU-intensive tasks, the best way to speed up the application and improve parallelizability is web workers. The web workers write the code off the main thread and offload tasks to a background thread.
The code running in the web worker cannot exist in the same JavaScript file in the application. These two must be different. Those working with tools such as Angular CLI bundles JavaScript automatically into a few files, as possible.
With the new improvements, Angular 8.0 makes it possible to fully parallelized web worker bundling. It acts as a relief for front-end developers who face limitations in single-thread.
You can run the following if you want to create a new CLI with a web worker.
ng generate web worker my-worker
On receiving the web worker, adopt the process to implement the web worker in your application. It is then bundled and code-split, correctly with the following:
const worker = new Worker(`./my-worker.worker`, { type: `module` });
Angular Router Backwards Compatibility
Angular 8 comes with backward compatibility mode which makes it simpler to upgrade the larger applications. The teams move to Angular with lazy loading of the AngularJS-based app’s parts, using the $route APIs.
FORMS
MarkAllAsTouched
MarkAllAsTouched is a method in Angular 8 used in AbstractControl class.
It adds to the list of previous methods such as markAsDirty, markAsTouched, and markAsPending. The method gets available in all reactive form entities since AbstractControl is the parent class of FormArray, FormGroup, and FormControl.
The method touches marks control and descendants as touched as shown below:
form.markAllAsTouched();
FormArray.clear
In Angular 8, the FormArray class offers a clear method. quickly removing all control it contains. It no longer requires to loop over control by one by one, as shown below:
// `users` is initialized with 2 usersconst users = fb.array([user1, user2]);users.clear();// users is now empty
ROUTER
Location
To migrate to Angular 8, a few things added to the location services of Angular are as follows:
- Offer access to the hostname, port, and protocol with platformLocation.
- Get history.state with new getState() method.
- Ease testing with a MockPlatformLocation.
Lazy-loading with import syntax
Lazy loading is a useful concept in Angular 8. It brings down the size of occasionally used files. It uses the standard dynamic import syntax ( ) from TypeScript, instead of the custom-string for lazy-loaded modules. The syntax has similarities with ECMAScript standard and supported only by Ivy.
So, what earlier looked like:
{ path: '/student', loadChildren: './student/student.module#StudentModule' } Now, looks as:{ path: '/student', loadChildren: () => import('./student/student.module').then(s => s.StudentModule) }
SERVICE WORKER
A service worker in Angular is a script that runs in a web browser and manages to cache for an application. It augments the traditional web deployment model and empowers the application – to deliver a reliable user experience and with a performance at par with natively-installed code.
Registration Strategy
In previous versions, the Service worker was waiting for a stable application to register. It was to avoid slowing the start of the application. The new option has an option that specifies when the registration will take place.
However, if starting a recurring asynchronous task in the previous versions would never be considered by Angular as stable, and service work would not have registered.
But, with Angular 8, this is possible with the option of a new registrationStrategy for handling the registration for the service worker with the following values:
- The default value is registerWhenStable.
- Register immediately with registerImmediately, with no need to wait for the app and registers, right away.
- Delay in milliseconds in $TIMEOUT with registerDelay:$TIMEOUT.
- A custom strategy defines a return value as Observable. The Service Worker registers with the first value of the Observable.
Here is code snippet for Service Worker registration after 4 seconds:
providers: [ ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production, registrationStrategy: 'registerDelay:4000' }), // ...]
Bypass a Service Worker
You can use the ngsw-bypass header, for bypassing the service worker with a specified request, as shown in the below code:
this.http.get(‘api/users’, { headers: { ‘ngsw-bypass’: true } });
Multiple Apps on SubDomains
Earlier it was not possible to use multiple applications for using @angular/service-worker with different sub-paths for the same domain. It was because the cache of each service worker overwrote the cache of others. This error gets fixed in this version.
TypeScript 3.4
It is now mandatory for Angular 8 to use TypeScript 3.4. The development team must upgrade the TypeScript. It helps when using readable and clean JavaScript code. TypeScript 3.4 introduces a new flag named incremental. It saves information from the project graph from the last compilation. While using Incremental, the information detects the least costly way to emit changes for your project and type-check.
Workspace APIs and Builder APIs in CLI
Angular 8 has new builder APIs to tap ng build, ng test, and ng run. It has similarities with schematics that taps into ng add,ng generate, ng update, and ng new.
It uses third-party tools and libraries to assist you in processes such as building and deployment. Moreover, Angular leverages Cloud for
APIs. AngularFire is the official library that connects Angular with Firebase. AngularFire adds the deploy command to simplify the process of deployment and build by Firebase with the following:
ng add @angular/fire
ng run my-app:deploy
Moreover, in the earlier version, for changes in workspace configuration, angular.json was modified manually using Schematics. But the new API, in the current version makes it simpler to modify and read a file.
AngularJS Migration
Angular 8 enables the users of $location services as it now allows a Location Upgrade Module in the AngularJS applications. It helps to translate the unified location service and shifts the responsibility from AngularJS $location to the Angular Location. It eases our applications with hybrid operations and depends on the upgrade along with route in AngularJS and part.
Bazel
The latest Angular version makes it easier to build CLI applications. All this is due to Bazel, developed by Google. It is a build tool that works well with any language inputs. Some benefits of Bazel are:
- Build frontend and backend with the same tool.
- Gain on rebuild time with tests and incremental builds.
- Gain cache and remote builds on build farms.
- Allow tasks with clear input or output with Bazel and ensure that all the necessary tasks run.
About IVY
Ivy is the prime feature of Angular 8 and included as an opt-in preview for testing. Ivy is a new compiler to build next-gen rendering pipeline in the current version. It increases the efficiency of the latest version. It helps to improve runtime speed with simplified incremental compiling with its ability to generate bundles of significantly smaller size.
Moreover, it uses the concept of incremental DOM, where each component gets compiled with a set of instructions that constitutes the DOM tree. It updates it with a change in data.
The developers can use Ivy to determine the potential and performance of Angular application. It never alters any of the existing applications. On completion, it will make the Angular applications smaller, simpler, and faster.
Two primary concepts of Ivy
Local : Recompile only the changed components and allow quicker compiling.
Treeshakable: The unused code gets removed so that the application concentrates on the code used. Ivy acts beneficially when the UI of the application is clear to the developer.
What are the Advantages of IVY?
The advantages for Ivy are:
- Smaller Bundles
- Reduced Payload Size
- Faster Rebuild times
- Enhance Backwards Compatibility
- Pre-compiled Code shipment
- Dismissal of metadata.json
- Rise of meta programming
- Improve template type checking
- Broad Compatibility with existing Angular applications
Notable Changes
Angular team makes your life easier with Schematics. Schematic updates your code by simply running:
ng update @angular/cor
Queries Timing
The decorators,ViewChild and ContentChild, now have a new option called static. If the queried element is static (not wrapped in ngIf and ngFor
then it is available in ngOnInit:
So,
<h1 #staticDiv>static</h1>Gives@ViewChild('staticDiv') staticDiv: ElementRef<HTMLDivElement>;ngOnInit() { console.log('init static', this.staticDiv); // div}ngAfterViewInit() { console.log('after view init static', this.staticDiv); // div}
A static flag, when introduced, not only breaks existing applications, and you can use the following to keep the old behavior, even when switching to Ivy. It ensures the same behavior as the current one.
@ViewChild('static', { static: true }) static: ElementRef<HTMLDivElement>;
You can check with the query migration guide for further information.
Template Variable ReAssignment
View Engine allowed the following:
<button *ngFor="let option of options" (click)="option = 'newButtonText'">{{ option }}</button>
However, this is no longer possible in Ivy. It does not allow us to assign a value to a template variable like an option in the above example.
When you upgrade to Angular 8, to prepare for the switch to Ivy, a schematic analyzes the template and issues a warning for such a case.
The option left is to fix it manually.
<button *ngFor="let option of options; index as index" (click)="options[index] = 'newButtonText'">{{ option }}</button>
Document
The token DOCUMENT gets moved from the @angular/platform-browser
to @angular/common. It is manually possible to change it with a schematic provided for the purpose.
Remove Deprecated HTTP Package
Angular 8 removed @angular/http replaced with @angular/common/http as in Angular 4.3. A schematic removes the dependency in package.json.
Deprecated Web Worker Package
@angular/common/http package enabled you to run an application in the Web Worker. It is included in the deprecated packages list and will get removed in the future.
You can find the list of all deprecated API packages obtained here.
How to Update Angular 7 to Angular 8?
Some of the things to consider are:
- TypeScript 3.4 may cause some syntax error
- Run $ node-vcommand for checking the version of Node running in your system. You need to run Node 12 and beyond for the upgradation
- Run $ ng update @angular/material to run the Angular Material in the application.
Conclusion
Other than Ivy, the additions to Angular 8 are not that critical but significant. You can gather insights on the Ivy preview from the official Ivy guide provided. However, it is recommended to upgrade to Angular 8 to ensure that your apps are all ready for Ivy.
Moreover, Ivy will become the default in the next version of Angular, so now it the best option for you to check whether your apps are going to need any changes.