Myths of Angular 2

What Angular Really Is

John Niedzwiecki

About the Geek

function getDeveloperInfo() {
    let dev = {
        name: 'John Niedzwiecki',
        company: 'ThreatTrack',
        role: 'Lead Software Engineer - UI',
        twitter: '@rhgeek',
        github: 'rhgeek',
        web: 'https://rhgeek.github.io',
        currentDevLoves: ['Angular', 'JavaScript Everywhere', 'd3', 'CSS instead of JS'],
        nonDevAttr : {
            isHusband: true,
            isFather: true,
            hobbies: ['running', 'disney', 'cooking', 'video games', 'photography'],
            twitter: '@rgrdisney',
            web: 'http://www.rungeekrundisney.com',
        }
    };
    return dev;
}

Why We're Here

At ng-Europe in 2014, the Angular team showed off Angular 2. Unfortunately, the drastic changes were not received well by many. While things have changed since that announcement during the development of Angular 2, many people remember the things said there instead of what was actually done (damn first impressions).

What We'll Do

  • What is Angular?
  • Version Soup
  • Mythbusting
  • Why Angular?

What is Angular?

What is Angular?

“Angular is a development platform for building mobile and desktop web applications.”

https://github.com/angular/angular

Component

/* /theme-parks/theme-parks-list/theme-parks-list.component.ts */
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ParksService, ThemeParkGroup } from '../../shared';

@Component({
  selector: 'app-theme-parks-list',
  templateUrl: './theme-parks-list.component.html',
  styleUrls: ['./theme-parks-list.component.css']
})
export class ThemeParksListComponent implements OnInit {

  themeParks: Observable< ThemeParkGroup[] >;

  constructor(
    private parksService: ParksService
  ) { }

  ngOnInit() {
    this.themeParks = this.parksService.getParks();
  }
}

Code: https://github.com/RHGeek/mythbusters-angular

Component Template


{{group.company}}

Location: {{group.location}}
# of Parks: {{group.parks.length}}

Component

/* /theme-parks/theme-park-details/theme-park-details.component.ts */
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { ParksService, ThemePark } from '../../shared';

@Component({
  selector: 'app-theme-park-details',
  templateUrl: './theme-park-details.component.html',
  styleUrls: ['./theme-park-details.component.css']
})
export class ThemeParkDetailsComponent implements OnInit {

  themePark: ThemePark;

  constructor(
    private route: ActivatedRoute,
    private parksService: ParksService
  ) { }

  canDeactivate(): Promise< boolean > | boolean {
    return new Promise< boolean >(resolve => {
      return resolve(window.confirm('Are you sure you\'re ready to leave the park?'));
    });
  }

  ngOnInit() {
    this.route.params
      .switchMap((params: Params) => this.parksService.getParkDetails(params['parkId']))
      .subscribe(
        (park: ThemePark) => {
          this.themePark = park;
        },
        error => {
          /* do error stuff here if you must */
        });
  }

}

Component Template


back

{{themePark?.company}}

Location: {{themePark?.location}}
Parks:
  • {{park.name}}

Services

/* /shared/parks.service.ts */
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { ThemePark } from './theme-park.model';
import { ThemeParkGroup } from './theme-park-group.model';

@Injectable()
export class ParksService {

  constructor(private http: Http) { }

  getParks(): Observable< ThemeParkGroup[] > {
    let url: string = `/api/parks/list`;
    return this.http.get(url)
            .map(response => response.json() as ThemeParkGroup[])
            .catch(this.handleError);
  }

  getParkDetails(parkId: string): Observable< ThemePark > {
    let url: string = `/api/parks/${parkId}`;
    return this.http.get(url)
            .map(response => response.json() as ThemePark)
            .catch(this.handleError);
  }

  private handleError(error: any): Observable {
      console.error('An error occurred', error);
      return Observable.throw(error.message || error);
  }
}

Improved Routing

/* /app-routing.module.ts */
import { NgModule }             from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CanDeactivateGuard } from './guards/';
import { ThemeParksComponent } from './theme-parks/theme-parks.component';
import { ThemeParksListComponent } from './theme-parks/theme-parks-list/theme-parks-list.component';
import { ThemeParkDetailsComponent } from './theme-parks/theme-park-details/theme-park-details.component';

const routes: Routes = [
    { path: '', redirectTo: 'parks', pathMatch: 'full' },
    { path: 'parks', component: ThemeParksComponent,
        children: [
            { path: '', redirectTo: 'list', pathMatch: 'full' },
            { path: 'list', component: ThemeParksListComponent },
            { path: 'details/:parkId', component: ThemeParkDetailsComponent, canDeactivate: [ CanDeactivateGuard ] }
        ]
    },
    { path: 'about', loadChildren: 'app/about/about.module#AboutModule' }
];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ],
    providers: [
        CanDeactivateGuard
    ]
})
export class AppRoutingModule { }

Child Outlets

/* /theme-parks.component.html */

{{greeting}}

Lazy Loading Modules

/* from previous routing code */
{ path: 'about', loadChildren: 'app/about/about.module#AboutModule' }

/* /about/about.module.ts */
import { NgModule } from '@angular/core';
import { CommonModule }   from '@angular/common';
import { AboutComponent } from './about.component';
import { AboutRoutingModule } from './about-routing.module';

@NgModule({
  declarations: [
    AboutComponent
  ],
  imports: [
    CommonModule,
    AboutRoutingModule
  ]
})
export class AboutModule { }

/* /about/about-routing.module.ts */
import { NgModule }             from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about.component';

const routes: Routes = [
    { path: '', component: AboutComponent }
];

@NgModule({
    imports: [ RouterModule.forChild(routes) ],
    exports: [ RouterModule ]
})
export class AboutRoutingModule { }

Let's see it

http://localhost:4200/

Angular or AngularJS?

AngularJS == 1.x

Angular == 2, 4, 6, 8...
who do we appreciate?
also may see things like ng2 or ngx

speaking of Angular 2 and Angular 4...

Semantic Versioning

Semantic Versioning

With new Angular release, the team announced the switch to Semantic Versioning (SEMVER).

What does it mean for you?

  • Future changes in a predictable way.
  • Time based release cycles.
  • Patch release each week, ~3 minor updates, and one major update every 6 months.

Breaking changes?

Angular 1 to Angular 2 was a complete rewrite. Angular jumped from version 2 to 4 to align the core packages versions (Angular's router was already version 3). Future major updates will be more standard "breaking changes" with proper documented deprecation phases.

Just Angular

From here on, it's just #angular.

MYTH: Evergreen Browsers Only

"Designed for the Future"

Angular 2 was designed "targeting modern browsers and using ECMAScript 6". This meant only evergreen, auto-updating browswers.

Source

Browser Support and Polyfills

Angular supports most recent browsers, on both desktop and mobile.

Chrome Firefox Edge IE Safari iOS Android IE mobile
latest latest 14 11 10 10 Marshmallow (6.0) 11
13 10 9 9 Lollipop (5.0, 5.1)
9 8 8 KitKat (4.4)
7 7 Jelly Bean (4.1, 4.2, 4.3)

Official Browser Support

Browser Support and Polyfills

https://github.com/angular/angular

Browser Support and Polyfills

There's a challenge in supporting the larger range of browsers. They offer mandatory and optional polyfills, depending on the browsers you want to support.

"Note that polyfills cannot magically transform an old, slow browser into a modern, fast one."

Source

Angular-CLI Provided polyfills.ts


/**
 * This file includes polyfills needed by Angular and is loaded before the app.
 * You can add your own extra polyfills to this file.
 *
 * This file is divided into 2 sections:
 *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
 *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
 *      file.
 *
 * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
 * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
 * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
 *
 * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
 */

/***************************************************************************************************
 * BROWSER POLYFILLS
 */

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js';  // Run `npm install --save classlist.js`.

/** IE10 and IE11 requires the following to support `@angular/animation`. */
import 'web-animations-js';  // Run `npm install --save web-animations-js`.


/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';


/** ALL Firefox browsers require the following to support `@angular/animation`. **/
import 'web-animations-js';  // Run `npm install --save web-animations-js`.



/***************************************************************************************************
 * Zone JS is required by Angular itself.
 */
import 'zone.js/dist/zone';  // Included with Angular CLI.



/***************************************************************************************************
 * APPLICATION IMPORTS
 */

/**
 * Date, currency, decimal and percent pipes.
 * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10
 */
import 'intl';  // Run `npm install --save intl`.

MYTH: Evergreen Browsers Only

¤

MYTH: No Migration Path

"We Will See"

Initially, no path to migration was announced. The team's goal was the best framework to build a web app without worrying backwards compatibility with existing APIs.

Obviously, people were less than happy for no concrete migration path.

Upgrading from AngularJS

Not only can you migrate an app, you can upgrade incrementally.

  • Follow Angular Style Guide
  • Use a module loader
  • Migrate to TypeScript
  • Use Component Directives

The Upgrade Module

This module allows you to run AngularJS and Angular components in the same application and interoperate with each other seemlessly.

Actually runs both versions of Angular side by side, no emulation. Interoperate via dependency injection, the DOM, and change detection.

More information: NgUpgrade

MYTH: No Migration Path

¤

MYTH: Base Angular App is HUGE

Base Angular Libraries Make a Simple App Huge

After the release, I've heard many arguments about the size of Angular files. It often pops up in comparisions of Angular vs React. You would see the comparison of Angular 2’s minified version (566K) to React JS with add-ons, minified version (144K).

Min size comparisions

Ahead of Time (AOT) Compilation

Non-issue for an Angular app thanks to AOT compilation. Angular built to take advantage of ES2015 module and tree shaking.

Proof of concept Hello World can be made in just 29KB

POC

Ahead of Time (AOT) Compilation

Angular 4 has made even larger improvements for AOT. The team has implemented a new View Engine to generate less code.

Two medium size apps improvement:
from 499Kb to 187Kb (68Kb to 34Kb after gzip)
from 192Kb to 82Kb (27Kb to 16Kb after gzip)

App stats

MYTH: Base Angular App is HUGE

¤

Why Angular?

Speed and Performance

I loved AngularJS, but there were performance issues (I'm looking at you dirty checking and digest cycles). Part of the reason for the rewrite for Angular 2 was to get things right, from the ground up.

Faster checking of single bindings, improved change detection strategies, Immutables, Observables, use of zone.js, AOT compiling, lazy loading modules

Angular Anywhere

  • Mobile Web
  • Desktop Web
  • Mobile Native (Angular + NativeScript)
  • Internet of Things (IoT)

Universal

Universal is more than just a theme park with some awesome Harry Potter lands. It's also the name of the official package for server side rendering in Angular.

Server side rendering can be important to single page apps (SPA). Everyone knows it matters for search engine optimization. It's also great to ensure you get that nifty little preview on social media.

Angular Universal

It's also great for perceived performance.

Angular Universal lets you render your app on the server, give it to the user, preboot a div to record their actions, and then replay and swap out once the app is bootstrapped.

https://universal.angular.io/

TSTypeScript: The thing you may be surprised to love

Frankly, I was worried about needing to use TypeScript going into Angular 2.

Then I used it.

Now, I <3 it.

Fantastic Tooling

  • Great IDE Integration
  • Great TypeScript tooling
  • AOT Compiling
  • Angular-CLI

Angular-CLI

Amazing command line tool for Angular applications.

https://cli.angular.io/

Community

Established community that has grown over many years.

Find me: @rhgeek

https://rhgeek.github.io/

Code: https://github.com/RHGeek/mythbusters-angular