Latest Features of Angular.js
Go in-depth on what's new in Angular.
Join the DZone community and get the full member experience.
Join For FreeThe 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 is 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 whether or not they should upgrade from Angular 7.0.
New Features of Angular 8.0
Differential Loading of JavaScript
Differential loading enables browsers to select optimized or legacy bundles according to their capabilities and then automatically load the correct one. Users then receive the bundle(s) they require based on their specific needs.
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, differential loading also helps in saving 7 to 20 percent of bundle size on average.
Differential loading in Angular 8.0 forms a part of Manfred Steyer's project, ngx-build-modern. All bundling is done with the ng build
command and the -prod
extension, without requiring special actions.
You may also like: Angular: Everything You Need to Know [Tutorials].
Opt-In Usage Sharing
It acts as an addition to the Angular CLI that aligns Angular 8 with community needs. Angular needs to keep a tab on how developers use the platform and what improvements are required. This is done with the information on the command used and builds speed. You can share telemetry on CLI usage with your development 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. Web workers write 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 as 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 with the following line:
const worker = new Worker(`./my-worker.worker`, { type: `module` });
Angular Router Backwards Compatibility
Angular 8 comes with a 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 the 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, which quickly removes all control it contains. You no longer have to loop over every control one-by-one, as shown below:
// `users` is initialized with 2 users
const users = fb.array([user1, user2]);
users.clear();
// users is now empty
ROUTER
Location
To migrate to Angular 8, you should be aware of a few things added to the location services:
- Offer access to the hostname, port, and protocol with
platformLocation
. - Get
history.state
with the newgetState()
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 cache for an application. It augments the traditional web deployment model and empowers the application to deliver a reliable user experience with performance on par with natively-installed code.
Registration Strategy
In previous versions, the Service worker was waiting for a stable application to register. This was used to avoid slowing the start of an 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, the service work would not have registered.
But, with Angular 8, this is possible with the option of registrationStrategy
for handling the registration for a 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
withregisterDelay:$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:
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 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 pipelines 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.
Developers can use Ivy to determine the potential and performance of Angular applications. 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.
Advantages of IVY
The advantages of 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
The angular team makes your life easier with Schematics. Schematic updates your code by simply running:
ng update @angular/cor
Query 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
. Thenm, 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, but 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
The @angular/common/http
package enables you to run an application in the Web Worker. It is included in the deprecated packages list and will be 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 the
$ node-vcommand
to check the version of Node running in your system. You need to run Node 12 and beyond for the upgrade. - 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 or 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.
Further Reading
Opinions expressed by DZone contributors are their own.
Trending
-
Integrating AWS With Salesforce Using Terraform
-
Java String Templates Today
-
You’ve Got Mail… and It’s a SPAM!
-
Boosting Application Performance With MicroStream and Redis Integration
Comments