How to Build OAuth App with Angular 7

How to Build OAuth App with Angular 7

Angular 7 was released earlier this quarter and I’m pumped about a few of its features. If you’ve been following Angular since Angular 2, you know that upgrading can sometimes be a pain.

If you’ve been following Angular since Angular 2, you know that upgrading can sometimes be a pain. There was no Angular 3, but upgrading to Angular 4 wasn’t too bad, aside from a bunch of changes in Angular’s testing infrastructure. Angular 4 to Angular 5 was painless, and 5 to 6 only required changes to classes that used RxJS.

Before I dive into showing you how to build an Angular app with authn/authz, let’s take a look at what’s new and noteworthy in this release.

Upgrade to Angular 7

If you created your app with Angular CLI, chances are you can easily upgrade to the latest release using ng update.

ng update @angular/cli @angular/core

You can also use the Angular Update Guide for complete step-by-step instructions.

What’s New in Angular 7

There are a few notable features in Angular 7, summarized below:

  • CLI prompts: this feature has been added to Schematics so you can prompt the user to make choices when running ng commands.
  • Performance enhancements: the Angular team found many people were using reflect-metadata as a dependency (rather than a dev-only dependency). If you update using the aforementioned methods, this dependency will automatically be moved. Angular 7 also adds bundle budgets so you’ll get warnings when your bundles exceed a particular size.
  • Angular Material: Material Design had significant updates in 2018 and Angular Material v7 reflects those updates.
  • Virtual Scrolling: this feature allows you to load/unload parts of a list based on visibility.
  • Drag and Drop: this feature has been added to the CDK of Angular Material.

Bundle budgets is the feature that excites me the most. I see a lot of Angular apps with large bundle sizes. You want your baseline cost to be minimal, so this feature should help. The following defaults are specified in angular.json when you create a new project with Angular CLI.

"budgets": [{
  "type": "initial",
  "maximumWarning": "2mb",
  "maximumError": "5mb"
}]

You can use Chrome’s data saver extension for maximum awareness of the data your app uses.

For more details on what’s new in Angular 7, see the Angular blog, coverage on InfoQ, or the Angular project’s changelog.

Now that you know how awesome Angular 7 is, let’s take a look at how to create secure applications with it!

Create a Secure Angular 7 Application

An easy way to create Angular 7 apps is using the Angular CLI. To install it, run the following command:

npm i -g @angular/cli

The example below uses Angular CLI 7.1.0. To verify you’re using the same version, you can run ng --version.

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/

Angular CLI: 7.1.0
Node: 11.1.0
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.11.0
@angular-devkit/core         7.1.0
@angular-devkit/schematics   7.1.0
@schematics/angular          7.1.0
@schematics/update           0.11.0
rxjs                         6.3.3
typescript                   3.1.6

To create a new app, run ng new ng-secure. When prompted for routing, type “Y“. The stylesheet format is not relevant to this example, so choose whatever you like. I used CSS.

After Angular CLI finishes creating your app, cd into its directory, run ng new, and navigate to http://localhost:4200 to see what it looks like.

Add Identity and Authentication to Your Angular 7 App with OIDC

If you’re developing apps for a large enterprise, you probably want to code them to use the same set of users. If you’re creating new user stores for each of your apps, stop it! There’s an easier way. You can use OpenID Connect (OIDC) to add authentication to your apps and allow them all to use the same user store.

OIDC requires an identity provider (or IdP). There are many well-known IdPs like Google, Twitter, and Facebook, but those services don’t allow you to manage your users like you would in Active Directory. Okta allows this, and you can use Okta’s API for OIDC.

Register for a forever-free developer account, and when you’re done, come on back so you can learn more about how to secure your Angular app!

Now that you have a developer account, I’ll show you several techniques for adding OIDC authentication to you Angular 7 app. But first, you’ll need to create a new OIDC app in Okta.

Create an OIDC App in Okta

Log in to your Okta Developer account and navigate to Applications > Add Application. Click Web and click Next. Give the app a name you’ll remember, and specify http://localhost:4200 as a Login redirect URI. Click Done. Edit your app after creating it and specify http://localhost:4200 as a Logout redirect URI too. The result should look something like the screenshot below.

Use angular-oauth2-oidc

The angular-oauth2-oidc library provides support for OAuth 2.0 and OIDC. It was originally created by Manfred Steyer and includes many community contributions.

Install angular-oauth2-oidc using the following command:

npm i [email protected]

Open src/app/app.module.ts and import OAuthModule as well as HttpClientModule.

import { HttpClientModule } from '@angular/common/http';
import { OAuthModule } from 'angular-oauth2-oidc';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Modify src/app/app.component.ts to import OAuthService and configure it to use your Okta application settings. Add login() and logout() methods, as well as a getter for the user’s name.

import { Component } from '@angular/core';
import { OAuthService, JwksValidationHandler, AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {
  issuer: 'https://{yourOktaDomain}/oauth2/default',
  redirectUri: window.location.origin,
  clientId: '{yourClientId}'
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-secure';

  constructor(private oauthService: OAuthService) {
    this.oauthService.configure(authConfig);
    this.oauthService.tokenValidationHandler = new JwksValidationHandler();
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  }

  login() {
    this.oauthService.initImplicitFlow();
  }

  logout() {
    this.oauthService.logOut();
  }

  get givenName() {
    const claims = this.oauthService.getIdentityClaims();
    if (!claims) {
      return null;
    }
    return claims['name'];
  }
}

Modify src/app/app.component.html to add Login and Logout buttons.

<h1>Welcome to {{ title }}!</h1>

<div *ngIf="givenName">
  <h2>Hi, {{givenName}}!</h2>
  <button (click)="logout()">Logout</button>
</div>

<div *ngIf="!givenName">
  <button (click)="login()">Login</button>
</div>

<router-outlet></router-outlet>

Restart your app and you should see a login button.

Click the login button, sign in to your Okta account, and you should see your name with a logout button.

Pretty slick, eh?

Okta’s Angular SDK

You can also use Okta’s Angular SDK to implement the same functionality. You can start by installing it.

npm i @okta/[email protected]

Change app.module.ts to configure your Okta settings and import the OktaAuthModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OktaAuthModule } from '@okta/okta-angular';

const config = {
  issuer: 'https://{yourOktaDomain}/oauth2/default',
  redirectUri: window.location.origin + '/implicit/callback',
  clientId: '{yourClientId}'
};

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    OktaAuthModule.initAuth(config)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

You might notice the redirect URI is a bit different than the previous one. For this to work, you’ll need to modify your Okta app and add http://localhost:4200/implicit/callback as a Login redirect URI.

Modify src/app/app-routing.ts to have a route for this path.

import { OktaCallbackComponent } from '@okta/okta-angular';

const routes: Routes = [
  {
    path: 'implicit/callback',
    component: OktaCallbackComponent
  }
];

Change app.component.ts to use the OktaAuthService to determine if the user is authenticated.

import { Component, OnInit } from '@angular/core';
import { OktaAuthService, UserClaims } from '@okta/okta-angular';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'ng-secure';
  isAuthenticated: boolean;
  email: string;

  constructor(public oktaAuth: OktaAuthService) {
  }

  async ngOnInit() {
    this.isAuthenticated = await this.oktaAuth.isAuthenticated();
    this.user = await this.oktaAuth.getUser();
    // Subscribe to authentication state changes
    this.oktaAuth.$authenticationState.subscribe( async(isAuthenticated: boolean)  => {
      this.isAuthenticated = isAuthenticated;
      this.user = await this.oktaAuth.getUser();
    });
  }
}

Then update app.component.html to use isAuthenticated and display the user’s name.

<h1>Welcome to {{ title }}!</h1>

<div *ngIf="isAuthenticated">
  <h2>Hi, {{user?.name}}!</h2>
  <button (click)="oktaAuth.logout()">Logout</button>
</div>

<div *ngIf="!isAuthenticated">
  <button (click)="oktaAuth.loginRedirect()">Login</button>
</div>

<router-outlet></router-outlet>

Restart your app and you should be able to log in to your app using Okta’s Angular SDK.

Use Authorization Code Flow

There is a new draft specification for OAuth called OAuth 2.0 for Browser-Based Apps. This was created by Okta’s own Aaron Parecki and contains an interesting clause.

The OAuth 2.0 Implicit grant authorization flow (defined in Section 4.2 of OAuth 2.0 [RFC6749]) works by receiving an access token in the HTTP redirect (front-channel) immediately without the code exchange step. The Implicit Flow cannot be protected by PKCE [RFC7636] (which is required according to Section 6), so clients and authorization servers MUST NOT use the Implicit Flow for browser-based apps.

Both angular-oauth2-oidc and Okta’s Angular SDK use implicit flow, the accepted practice prior to the recent discussion in Aaron’s draft specification. So how do you follow Aaron’s recommendation and use authorization code flow with PKCE in your Angular app? There are a couple options:

I tried using angular-oauth2-oidc-codeflow with Okta. I used the code from my angular-oauth2-oidc example above and found I only needed to change a few things (after installing it with npm i angular-oauth2-oidc-codeflow):

  1. Imports should be from 'angular-oauth2-oidc-codeflow'
  2. The login() method in AppComponent should be changed to use auth code flow.
    login() {
      this.oauthService.initAuthorizationCodeFlow();
    }

After making these changes, I tried to log in to my original SPA app. The error I received was unsupported_response_type. I tried creating a new Native app with PKCE, but it failed because angular-oauth2-oidc-codeflow does not send a code challenge.

In my Build a Desktop App with Electron and Authentication, I successfully used AppAuth and PKCE. The reason this works is because it’s a desktop app and doesn’t send an origin header. Okta’s token endpoint doesn’t allow CORS (cross-origin resource sharing), so it won’t work in a browser client.

We hope to fix this soon. As the industry evolves, we’ll do our best to keep our libraries current with best practices. In the meantime, we recommend you use a CSP (content security policy) to make sure 3rd party scripts don’t have access to your Angular app.

See 10 Excellent Ways to Secure Your Spring Boot Application to see how to add a CSP with Spring Boot.

You might also find Micah Silverman’s PKCE Command Line project interesting.

Limit Access Based on Group for Your Angular 7 App

If you’d like to show/hide components of your app based on a user’s group, you’ll need to add a “groups” claim to your ID token. Log in to your Okta account, navigate to API > Authorization Servers, click the Authorization Servers tab and edit the default one. Click the Claims tab and Add Claim. Name it “groups”, and include it in the ID Token. Set the value type to “Groups” and set the filter to be a Regex of .*.

Now you can create an Angular directive to show/hide elements based on the user’s groups. There is currently an open issue that shows how you might go about doing this.

Control Access to Routes with an AuthGuard

Angular’s router documentation includes an example of how to create an AuthGuard to protect routes so they’re only available to authenticated users.

Okta’s Angular SDK ships with an OktaAuthGuard that you can use to protect your routes. It verifies there is a valid access token before allowing the user to navigate to the route. Below is an example of how to configure it in app-routing.module.ts.

import { OktaAuthGuard } from '@okta/okta-angular';

const routes: Routes = [
  { path: 'secure', component: MySecureComponent, canActivate: [OktaAuthGuard] }
]

You can implement a similar auth guard for angular-oauth2-oidc as shown in Angular Authentication with OpenID Connect and Okta in 20 Minutes.

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private oauthService: OAuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.oauthService.hasValidIdToken()) {
      return true;
    }

    this.router.navigate(['/']);
    return false;
  }
}

Angular 7 CLI Tutorial and Angular 7 CRUD with Spring Boot

Phew, that’s a lot of information about authentication with Angular 7! For more straightforward Angular content, I invite you to take a look at a couple tutorials I recently upgraded to Angular 7.

I updated a few of my tutorials to use Angular 7 recently.

In fact, I enjoyed playing with Angular 7 so much, I turned the basic CRUD app tutorial into a screencast!

JHipster and Angular 7

I’m a committer on a project called JHipster. JHipster allows you to generate a Spring Boot app with an Angular UI quickly and easily. The JHipster team upgraded to Angular 7 in its 5.6.0 release. You can create a JHipster app with Angular using a single JDL file. JDL stands for JHipster Domain Language.

To see JHipster in action, install it using npm i generator-jhipster and create an app.jh file with the following JDL.

application {
  config {
    baseName blog,
    applicationType monolith,
    packageName com.jhipster.demo.blog,
    prodDatabaseType mysql,
    cacheProvider hazelcast,
    buildTool maven,
    clientFramework angular,
    useSass true,
    testFrameworks [protractor]
  }
}

JHipster uses JWT authentication by default, but you can switch it to use OIDC for authentication pretty easily (hint: just add authenticationType oauth2 to app.jh).

Create a blog directory and run jhipster import-jdl app.jh inside of it. In a minute or two, you’ll have a fully functional (and well-tested) Spring Boot + Angular + Bootstrap app! If you want to add entities to CRUD, see this sample JDL.

The sample JDL mentioned uses React for its clientFramework. Make sure to change it to angular to use Angular 7.

If you’ve never heard of JHipster before, you should download the free JHipster Mini-Book from InfoQ! It’s a book I wrote to help you get started with hip technologies today: Angular, Bootstrap and Spring Boot. The 5.0 version was recently released.

Node vs Angular : Comparing Two Strong JavaScript Technologies

Just from being a simple client-side scripting language, JavaScript has evolved over the years to turn out to be a powerful programming language. Here Node.js is a cross-platform runtime environment while AngularJS is one of the top JavaScript framework. Angular helps the developers to build web applications which are dynamic in nature using HTML template language and following the MVC design pattern.

An Angular Roadmap — The Past, Present, and Future of Angular

An Angular Roadmap — The Past, Present, and Future of Angular

✅Interested in being an Angular developer in 2019? ... blog post it's most likely that you've written some code in javaScript in the past.

Paleolithic JavaScript — SproutCore

In the beginning, there was SproutCore. It was the first comprehensive JavaScript framework aimed at making it easy to build desktop-quality single-page web apps. It’s not that this wasn’t possible before. When Google released Gmail, it showed the world that web apps really could replace complex desktop applications. Google even open-sourced the Closure toolkit — a set of libraries and an optimizing compiler that it used to build Gmail.

The problem was that Google’s Closure tools weren’t very developer-friendly. They relied heavily on Java, which alienated web developers who were used to working with JavaScript, PHP, Ruby, and Python. Gmail was a great demonstration of what was possible, but developing similar applications still felt out of reach for many.

Some courageous developers managed to string together amazing single page apps using a combination of jQuery, duct tape, and hope. While these apps looked amazing to end-users, for the developers working on them, the apps quickly turned into hulking piles of technical debt that made the dev team dread heading to work in the morning.

As a result, a few enterprising developers began to work on frameworks that would bring Gmail-like apps within easy reach of web developers everywhere. SproutCore was the first of these frameworks to take off. It came with a complete set of widgets that made it possible to build complex web applications without even touching HTML or CSS.

This ended up being great for former desktop developers who had been dragged kicking and screaming onto the web. Several more frameworks popped up with similar goals; GWT and Cappuccino were the most prominent. These frameworks even avoided JavaScript by transpiling other languages into JS. Again, this was great for desktop developers. But it left passionate web developers out in the cold and made them feel as though their hard-won HTML, CSS, and JavaScript skills weren’t valuable.

This left an opening for a framework that truly embraced the web, instead of trying to plaster over it and pretend it was something else. A couple of early frameworks (Backbone and Knockout) appeared, and achieved a moderate amount of success. Ember also showed up around this time. It took SproutCore, stripped it down to its bones, and tried to rebuild it into something truly web-friendly. Ember wanted to be the Six Million Dollar Man of the JavaScript world: rebuilt better, stronger, and faster.

None of these frameworks rocketed to popularity. The world was waiting for something better. In 2010, that something better appeared — it was named Angular.

The Golden Age of Angular

Even before Angular version 1.0 had been released, Angular took the front-end development world by storm. Finally, we had an easy-to-use JavaScript framework that treated HTML as a first-class citizen. Developers and designers could now work together to build amazing single-page applications. This came as a relief to designers, who had been annoyed and offended because older frameworks had treated HTML and CSS as tools for barbarians, tools that no civilized developer should have to touch.

The first thing that seemed magical to developers trying Angular for the first time was two-way data binding. Prior to this, most developers had only seen this kind of data binding in desktop frameworks like WPF and Windows Forms. It was great to be able to bind forms and other UI elements to JavaScript model objects. While two-way data binding could cause performance problems when overused, teams that used it judiciously found that Angular enabled them to create complex front-end applications much more quickly than ever before.

Angular proved to be popular for more than just easy binding of data to HTML elements. Angular directives provided an easy way to create reusable HTML + CSS components. Although other JavaScript frameworks provided this before Angular, Angular was the first one that became extremely popular. Reusable components had long been in-use in server-side frameworks. ASP.NET user controls and partial templates in Rails and Django are but a few examples.

Finally, Angular made dependency injection popular in the front-end development world. Dependency injection had long been popular in enterprise applications, which is perhaps why it hadn’t caught on in the JavaScript world. Front-end developers have long been averse to what they see as needlessly complex enterprise software design patterns. This concern isn’t without merit. Have you ever, in the course of writing an application, said to yourself “What I really need here is a “SimpleBeanFactoryAwareAspectInstanceFactory?”

Dependency injection, though, has proven its worth. And Angular made dependency injection easy to use for an audience that hadn’t used it much in the past. Need an HTTP client? Or perhaps you’d like to do some animation? No problem. Angular had built-in services for those. Just ask for them, and Angular would inject them into your components. No need to instantiate anything yourself.

Or perhaps you wanted to use the browser’s window or location objects without making it impossible to unit test your components outside of a browser? Angular had you covered there too, with its built-in $window and $location services. At runtime, you’d get the browser objects you were expecting. And when running unit tests server-side in Node.js, you could pass mock services into your components to ensure they behaved as expected in various scenarios.

If all of this wasn’t enough, Angular also made it simple to register and inject your own services. For developers who were used to binding all their data to the DOM and hoping for the best, this was awesome. If you were writing a new front-end app that called for APIs that would cost your company a lot of money if overused, you’d probably prefer to be able to write tests ahead of time to ensure that your application doesn’t try to do something like calling the Twilio API 800 million times.

So you’d create a Twilio service that gets injected at runtime. At testing time, you’d create a mock service that records the cost of every API call your application is trying to make. You’d write tests that cover common usage scenarios and ensure that these scenarios don’t result in your company receiving a 7-figure bill. Overall, most developers found that Angular directives combined with dependency injection made it possible to write modular, testable front-end applications using tried-and-true software engineering techniques. Many development teams decided that this resulted in a happy state of affairs, and decided to go all-in on Angular.

The Angular Decline? The Rise of React

While things were mostly great in the world of Angular, it wasn’t all sunshine and lollipops. Developers were starting to run into severe performance problems when they tried to bind too many model objects to too many DOM elements. Some applications slowed to a crawl. Direct calls to $digest and other black-magic sorcery started becoming necessary to achieve acceptable performance. Around the same time, a new challenger appeared: React. At first, React didn’t seem to pose too large a danger to Angular. After all, these React weirdos had gone to the trouble of inventing JSX, which looked a lot like a way to mix markup into your code. Hadn’t we gone to a lot of trouble to invent templating languages for the explicit reason of avoiding mixing markup and code?

As it turned out, React’s approach was pretty popular in the front-end development community. It didn’t rocket to popularity, however. Angular was still dominant, and it looked like it would remain that way. Until that is, Angular’s popularity was given a good kick in the teeth from an unexpected source: the Angular team itself.

The Introduction of Angular 2

Angular 2 was first announced at the ng-europe conference in 2014. The Angular team’s plans came as a shock to the Angular community, to say the least. Reaction from Angular developers was swift and negative… and not without reason. Angular 2 would be getting rid of many familiar concepts from Angular 1, introducing a new, incompatible templating language (and oh, by the way) would also be programmed using an entirely new language.

AngularJS

Although both Angular 1 and Angular 2 were called ‘Angular,’ in reality, they were very different frameworks with a few things in common. To help prevent confusion, the Angular team started referring to the old version of Angular as ‘AngularJS’, and the new version as simply ‘Angular.’ This makes intuitive sense since AngularJS was written in JavaScript, and Angular was not. To keep the distinction between the frameworks clear, I’ll be referring to Angular 1 as AngularJS from this point forward.

As a result of all of this, AngularJS developers lost faith in the framework’s future. They threatened to move to a new framework on future projects, and that is precisely what many of them did. React was the biggest beneficiary of the mass exodus from AngularJS.

Although React didn’t do as much as AngularJS, in a way that was positive. If you’re using a view library that doesn’t try to include everything plus the kitchen sink, it’s a lot more difficult for the developers of that library to pull the rug out from under you in the future. In the beginning, using React was a bit of a pain compared to AngularJS. You had to cobble together a patchwork of libraries just to cover the functionality the AngularJS provided out of the box.

Many teams saw this as a good way to reduce risk, because it was unlikely that the developers of all of those libraries would decide to make backward incompatible breaking changes at the same time, which is essentially what Angular had done.

The Emergence of Vue

To compound AngularJS’ woes, another framework named Vue showed up at about the same time the drama over Angular 2 was occurring. Vue was inspired by AngularJS but aimed to simplify it and get rid of what Vue’s creator saw as unnecessary complexity (so Vue felt very familiar to existing AngularJS developers). Vue provided a safe haven for many AngularJS developers who didn’t want to move over to React.

This doesn’t mean that AngularJS developers were not waiting patiently for Angular 2 to appear. But it’s clear that there was a mass exodus from AngularJS to React and Vue due to the uncertainty caused by the plans for Angular 2.

Rising From the Ashes with Angular 2

Eventually, Angular 2 was released. As expected, it did away with many familiar concepts from AngularJS but kept a few of the best pieces like services and dependency injection. Fortunately for the sanity of developers, Angular uses plain TypeScript and not a fork as originally planned.

To make things more confusing, the Angular team maintained a fork of the new framework that used the Dart programming language instead of TypeScript. Initially, the TypeScript and Dart versions were developed in sync, generated from a single code base. Eventually, the TS and Dart versions of Angular decided to go their separate ways, and Angular Dart now exists on its own.

Even with this confusion, Angular’s popularity began to increase again after the Angular 2 release. It happened slowly. As often occurs in software development, trends shifted. Developers realized that a big, batteries-included framework might actually be useful. After all, when your application grows large enough, you end up actually needing all of those batteries.

Enterprise developers, in particular, began moving back to Angular. This makes sense. Usually, when you start an enterprise web app, you know it is going to be complex. There’s no point in starting with a tiny MVP when you know from the beginning all 87 things your application is going to be expected to do.

Where’s Angular 3?

Although Angular 2 wasn’t perfect, many developers of complex web applications began to realize that the new-and-improved Angular was a good fit for their needs. Fortunately for them, Angular had some exciting improvements in store. More importantly, the Angular team demonstrated that it could consistently publish new versions of the framework with few breaking changes between versions

In a move that seemed odd at the time, the Angular team decided to skip version 3 entirely and move to version 4. This was done for good reason: the team working on Angular’s router package had already pushed ahead and released version 3, while the remainder of Angular was still at version 2.3. They decided to keep all Angular package versions in sync moving forward, and bumping everything up to version 4 for the next release was the easiest way to achieve this.

Angular 4

Angular 4 had some significant changes, including added ahead of time compilation, which resulted in small production JavaScript bundles and shorter application load time. Support for server-side rendering was added, which was a boost for teams that wanted to render their app ahead of time to improve initial load performance. Many other improvements were added throughout the framework, but upgrading apps from Angular 2 to 4 was quick and painless in most cases.

Angular 4.3 and Angular 5

Angular 4.3 added a new HTTP client that was easier to use than the old HTTP service. In Angular 5, the old HTTP service was deprecated and would be dropped in the next release. In spite of this inconvenience, there was relatively little grumbling because the upgrade in most cases was straightforward. Angular 5 also added better internationalization support and further build optimizations.

Angular 6 and 7

Angular 6 and 7 were disappointing to some developers. There were no large changes, but there were many small quality of life improvements, especially to the Angular CLI tooling. The decreasing number of visible changes isn’t an indication that the Angular team has stopped innovating. Instead, it shows that the framework is mature, so the development team is now free to do more work behind the scenes, fixing bugs and improving performance.

The stability of the framework since the release of Angular 2 has drawn some old-school AngularJS developers back into the Angular world. It has also attracted the attention of enterprise development teams. When you’re building enterprise apps that may live for decades it’s ideal to use a framework that gets new releases on a predictable schedule but doesn’t change too rapidly. A developer who had only used Angular 2 could be up and running and contributing to an Angular 7 app within minutes.

The Future of Angular

Angular 8 and Angular Ivy

And that brings us to today. As we’ve seen, Angular has come a long way. It has gone from loved by web developers to being reviled to being admired, although it isn’t yet loved again like it was in its early days.

On the horizon, we have Angular 8. A ton of work has been done in Angular 8 to make it easy to use with the Bazel build system, which is absolutely amazing news for all 3 developers who are using it outside of Google. More excitingly, though, the Angular team is hard at work on a new rendered called Angular Ivy. It’s intended to be a drop-in replacement for the current rendered. For the most part, current apps won’t need to make any changes to use Angular Ivy.

If Angular Ivy is a drop-in replacement, why should developers care? Two important reasons: speed, and bundle size — two very important concerns. For a few years, it seemed like web developers had gone a bit crazy. Teams were shipping JavaScript bundles that were 5MB, 10MB, or even larger, and thinking that there was no problem with this. After all, the applications worked perfectly on the developers’ i7-powered MacBook Pros so they should work fine for everyone, right?

Unfortunately, in the real world, not everyone is running the latest and greatest hardware. Hundreds of millions of people access the internet solely on older Android phones with slightly more processing power than a potato, through internet connections only a little faster than dial-up. For these users, a huge JavaScript bundle takes forever to load, and even longer for their device to parse and run. Even in less extreme cases, there are countless users around the world who aren’t using the latest and greatest hardware. For them, massive JavaScript apps are usable (but painful).

Angular Ivy Expectations

The Angular Ivy renderer will help in several ways:

  1. It is being written with an eye on efficiency, so it will accomplish the same tasks while executing far fewer CPU instructions. This will improve both the battery life and the sanity of users with less-than-powerful devices.
  2. The renderer will be written in a much more modular fashion that the current renderer. This will make it much more amenable to tree-shaking and dead code elimination. As a result, your production JavaScript bundle will include only the code that is needed to run your application, instead of bundling together everything plus the kitchen sink as often happens with the current rendered.
  3. In addition to the bundle-size reduction and improved rendering speed, Angular Ivy has another few quality-of-life enhancements for Angular developers. Rebuild times are significantly faster. So if you’re running your app in development mode and waiting for your changes to appear, you’re now going to be spending a lot less time waiting.
  4. Template-type checking is improved, which means you’ll catch more errors at compile time instead of at runtime. Runtime template bugs are annoying, because they either bite you during testing, or they bite your users when they’re trying to use your app.
  5. The Angular Ivy template compiler will generate code that is human readable, which the current View Engine compiler doesn’t do. This will come in handy when trying to track down tough template bugs.

The net result: smaller apps, faster apps, happier developers, and happier users.

Angular’s Past, Present, and Future

If you’ve been using Angular from its early days all the way until now, then congratulations! While there have been plenty of rough patches, we’ve ended up with a fast, modern framework that is fun to use.

If you were an AngularJS developer but moved on to React, Vue, or something else, I encourage you to give Angular another look. It’s worth your time, even if you decide to stick with what you’re using now.

And if you’ve never used Angular at all, why not give it a shot?

We’ve just been on a whirlwind tour through Angular’s past, present, and future. Without a doubt, it has been quite a ride. Regardless of your Angular background, I hope you’ve enjoyed the tour!

30s ad

Angular 2 Firebase - Build a Web App with Typescript

Angular 2 Demystified

Master Angular 2 - The No Nonsense Course

Complete Angular 7 - Ultimate Guide - with Real World App

A Quick Guide to Angular 7 in 4 Hours