Angular 8 is the latest version of Google's Angular – one of the best JavaScript frameworks around. In this article, we'll run through what's special about Angular 8, and show you how to get started. First, a brief look back at what's happened with the framework so far.
Angular's introduction led to a paradigm shift in web development: while most libraries limited themselves to providing support to developers with relatively limited architectural impact, Angular's developer team went in the other direction. Their product forces you to use a specific architecture, with deviations ranging from difficult to commercially pointless. In fact, most Angular code runs through a relatively complex transpilation toolchain before it ever hits the browser.
Due to the immense success of Angular, both inside and outside of Google Inc, development has – by and large – stabilised. This means that breaking code changes are few, while the semi-annual upgrades are focused on adapting the framework to changes in the web browsing landscape.
In the case of Angular 8, for example, a new JavaScript compiler is deployed (albeit still experimentally). It optimises generated compatibility code to be significantly smaller and faster at the expense of older browsers. Furthermore, Web Worker support is integrated to increase Angular's processing capability. In short, there is a lot to see – so let us dive right in.
If you'd rather design a site without code, try one of these easy website builders. And to make things run even smoother, get your web hosting service right.
01. Run a version check
Angular's toolchain lives inside the NodeJS environment. As of this writing, Node.js 10.9 or better is needed – if you find yourself on an older version, visit the Node.js website and get an upgrade. The code below shows the version status on this machine.
tamhan@TAMHAN18:~$ node -v
v12.4.0
tamhan@TAMHAN18:~$ npm -v
6.9.0
02. Install Angular
Angular's toolchain resides in a command line utility named ng. It can be installed via the well-known NPM.
Get top Black Friday deals sent straight to your inbox: Sign up now!
We curate the best offers on creative kit and give our expert recommendations to save you time this Black Friday. Upgrade your setup for less with Creative Bloq.
tamhan@TAMHAN18:~$ sudo npm install -g @angular/cli
tamhan@TAMHAN18:~$ ng version
Be careful to answer the question shown in the image below.
Getting version info out of the tool is quite difficult – not only is the syntax unique, but the output is also verbose (see image below).
03. Create a project skeleton
ng generates the Angular scaffolding for us. In the following steps, we want to add routing, and use Sass for CSS transpilation. Should the deployment fail for some reason, empty the working directory, and restart ng with superuser rights.
tamhan@TAMHAN18:~$ mkdir angularspace
tamhan@TAMHAN18:~$ cd angularspace/
tamhan@TAMHAN18:~/angularspace$ ng new workertest
04. Harness differential loading
The new version of Angular optimises backward compatiblity code for reduced impact – a file called browserslist lets you decide which browsers are to be supported. Open browserslist and remove the word not in front of IE 9 to IE11.
. . .
> 0.5%
last 2 versions
Firefox ESR
not dead
IE 9-11 # For IE 9-11 support, remove 'not'.
05. ... and see the results
Order a compile of the project, change into the distribution folder and purge unneeded map files.
tamhan@TAMHAN18:~/angularspace/workertest$
sudo ng build
tamhan@TAMHAN18:~/angularspace/workertest/dist/workertest$ ls
Invoke tree to see the results – ng creates multiple versions of various code files (see image below).
06. Spawn a web worker
Web workers let JavaScript enter the last frontier of native applications: massively parallel processing of tasks. With Angular 8, a web worker can be created right from the comfort of the ng command line utility.
tamhan@TAMHAN18:~/angularspace/workertest$
sudo ng generate web-worker myworker
CREATE tsconfig.worker.json (212 bytes)
CREATE src/app/myworker.worker.ts (157 bytes)
UPDATE tsconfig.app.json (236 bytes)
UPDATE angular.json (3640 bytes)
07. Explore the code
ng's output is likely to look intimidating at first glance. Opening the file src/app/myworker.worker.ts in a code editor of choice reveals code which you should know well from the WebWorker specification. In principle, the worker receives messages and processes them as needed.
/// <reference lib="webworker" />
addEventListener('message', ({ data }) => {
const response = `worker response to
${data}`;
postMessage(response);
});
08. Set up scaffolding
Angular applications consist of components. Firing off our web worker is best done inside the AppComponent, which is expanded to include a listener for the OnInit event. For now, it will emit status information only.
import { Component, OnInit } from '@angular/core';
@Component({
. . .
})
export class AppComponent implements OnInit {
title = 'workertest';
ngOnInit() {
console.log("AppComponent: OnInit()");
}
}
09. Don't worry about the lack of constructor
Experienced TypeScript developers ask themselves why our code does not use the constructor provided by the programming language. The reason for that is that ngOnInit is a lifecycle event which gets fired whenever an initialisation event takes place – this does not need to be correlated to class invocation.
10. Execute a small compile run
At this point in time, the program is ready to run. We will execute it from the server inside of ng, which can be invoked via the serve command. A neat aspect of this approach is that the program detects changes and recompiles the project on the fly.
tamhan@TAMHAN18:~/angularspace/workertest$
sudo ng serve
Take a look at the figure to see this in action in the image below.
11. ...and find the output
ng serve putputs the address of its local web server, which is usually http://localhost:4200/. Open the web page and open the developer tools to see the status output. Keep in mind that console.log outputs data to the browser console and leaves the console of the NodeJS instance untouched.
12. Get to work
At this point in time, we create an instance of the worker and provide it with a message. Its results are then shown in the browser console.
if (typeof Worker !== 'undefined') {
// Create a new
const worker = new Worker('./myworker.worker', { type: 'module' });
worker.onmessage = ({ data }) => {
console.log('page got message: $\
{data\}');
};
worker.postMessage('hello');
} else {
console.log("No worker support");
}
13. Explore Ivy
Future versions of Angular will use a more advanced compiler, leading to even smaller views. While the product is not finished yet, an ivy-enabled skeleton can be spawned via ng new ivy-project – enable-ivy. Alternatively, change the compiler settings as shown in the snippet.
"angularCompilerOptions": {
"enableIvy": true
}
A word of warning: Ivy leads to amazing size reductions, but it is not free. The product has yet to stabilize, so using it in productive environments is not recommended.
14. Try modified ng processing
Angular's ng command line tool used child scripts internally for some time. Angular 8 ups the ante in that you can now, also, use this facility to run your own tasks as your application is assembled and compiled.
"architect": {
"build": {
"builder": "@angular-devkit/
build-angular:browser",
One neat application of ng scripts involves directly uploading applications to cloud services. The Git repository provides a useful script that uploads your work to a Firebase account.
15. Enjoy improved migration
Developers migrating away from Angular 1.x, also known as AngularJS, have had a fair share of issues getting the navigator to work right in 'combined' applications. The new Unified Location Service aims to make this process smoother.
16. Explore workspace control
Large projects benefit from the ability to change the workspace structure dynamically. This is done via the new Workspace API introduced in Angular 8.0 – the snippet accompanying this step provides a quick overview of the behaviour.
async function demonstrate() {
const host = workspaces.
createWorkspaceHost(new NodeJsSyncHost());
const workspace = await workspaces.
readWorkspace('path/to/workspace/directory/',
host);
const project = workspace.projects.
get('my-app');
const buildTarget = project.targets.
get('build');
buildTarget.options.optimization = true;
await workspaces.writeWorkspace(workspace,
host);
}
17. Accelerate the process
Building large JavaScript code bases gets tedious. Future versions of AngularJS will use Google's Bazel build system to accelerate the process – sadly, at time of writing it wasn't ready for primetime.
18. Avoid the walking dead
Even though Google takes extreme care not to break code, some features simply need to be removed as they are no longer needed. Check this depreciations list to learn more about features which should be avoided.
19. Look at the change log
As always, one article can never do justice to an entire release. Fortunately, this change log provides a detailed list of all the changes – just in case you ever feel like checking the pulse of a feature especially dear to you.
Got a lot of files ready for upload to your site? Back them up in the most reliable cloud storage.
This article was originally published in creative web design magazine Web Designer.
Read more:
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
Tam Hanna is a software consultant who specialises in the management of carrier and device manufacturer relationships, mobile application distribution and development, design and prototyping of process computers and sensors. He was a regular contributor to Web Designer magazine in previous years, and now occupies his time as the owner of Tamoggemon Software and Computer Software.