Angular 2: First Look

Kevin O'Shaughnessy
14 min readMay 21, 2016

--

John Papa

Welcome to this review of the Pluralsight course Angular 2: First Look by John Papa.

John is a Google Developer Expert, Microsoft Regional Director and MVP, author of 100+ articles and 10 books, and a former technology Evangelist for Microsoft client teams.

His website johnpapa.net contains many useful articles on Angular 2 and other web technology.

Pluralsight describe Angular 2: First Look as:

“a gentle introduction to the changes that Angular 2 brings, how they compare to Angular 1, and provides an understanding of the architecture and how the core concepts work together to build applications.”

Related Courses

Deborah Kurata has a beginner friendly course Angular 2: Getting Started, which does not assume any previous knowledge of the first version of Angular JS.

Angular 2: First Look uses Dan Wahlin and John Papa have produced a TypeScript Fundamentals course. I have previously watched this and can recommend it if you have no previous experience with this language.

Angular 1.x vs Angular 2.x

At the time of writing (31st May 2016) Angular 2 has reached release candidate status.

Although many people will now choose Angular 2 over Angular 1, it is not necessarily a but choice to adopt the latest version of Angular 1.x into your project.

As Angular 2 is more or less a ground up rewrite of Angular 1.x, I find it useful evaluate them as separate frameworks rather than.

Angular 1.x is a much more mature framework. If you want to use Angular UI, or Ionic 1.x, you will currently need to use Angular 1.x.

If you decide to learn Angular 1.x, there are many courses available, a whole learning path and more.

The benefits that Angular 2 has over Angular 1.x are detailed in this course. By the end of this course, I was satisfied that Angular 2 is in many ways far superior to Angular 1.

If you are going to start a new project in Angular 1, I recommend thinking about a strategy for migrating away from it at a later date.

Angular 2 in Action

Angular

We learn that this is a “big picture” course — the first course on Angular 2 released from Pluralsight.

This clip mentions translating your existing Angular 1 skills, but John says previous knowledge of Angular 1, while helpful, is not required for this course.

If you are new to JavaScript, in my opinion you should not learn Angular JS yet, and should look at the JavaScript learning path, which I have watched and reviewed for you recently.

John briefly explains some reasons why you may want to use Angular 2. This does not compare this framework against others. I will be doing that this year, and the beginning of that work can be found here.

What Can We Build?

John introduces some of the software built in this course.

Running the Samples

Even if you don’t have a Pluralsight subscription, you can find same code at http://a2-first-look.azurewebsites.net/

These examples run in the browser so there is no installation required. There are also Angular 1 examples included here so that we can see the comparison.

Angular 2 Architecture, What’s New and What’s Different

Language Choices

Here John explains the different options we have: ES5, ES2015, TypeScript and Dart.

Angular 1’s Impact

John mention’s Brad Green’s figure of 1.1 million Angular developers.

You can find Brad Green’s AngularConnect keynote here.

Controller to Components

We see Angular 1 Controller code, and Angular 2 Component code, side by side.

First Look at Components

John introduces the essentials of how components work in Angular 2. If this doesn’t yet make a lot of sense, don’t worry because it will be covered in more detail soon.

Bootstrapping Angular

Again we compare Angular 1 and 2 side by side and see that where we used to write HTML in Angular, we write code in Angular 2.

Structural Directives

This is quite similar between Angular 1 and 2. We see that ng-repeat is being replace with *ng-for

First Look at Structural Directives

A quick look at the Structural Directives code.

Data Binding

Data binding means getting our code to update the DOM.

There are four different options for doing data binding:

  • Interpolation
  • One Way Binding
  • Event Binding
  • Two Way Binding

We see side by side Angular 1 and 2 examples of each of these.

There’s a little less Interpolation code in Angular 2 because we already know the context.

We see the square bracket notation in Angular 2 in the One Way Binding example.

We see the round bracket notation in the Event Binding example.

And we see both square and round brackets in the Two Way Binding example. This is known as “banana in a box” [()]

First Look at Data Binding

In this clip John shows you the Two Way Data Binding code example.

Fewer Built-in Directives

We see the mess of Angular 1 directives, and how Angular 2 is now less messy.

John says that more than 40 Angular 1 directives have been removed in Angular 2.

We see some examples: click, focus, blur and keyup.

First Look at HTML Element Property and Event Binding

In this clip John shows you the Property Binding code example. There’s less code needed when using Angular 2.

Services and Dependency Injection

There are two separate topics discussed in the clip.

First we see a side by side example of how Angular 2 simplifies services.

Then John shows us that Dependency Injection registration is very different in Angular 2; it is now specified in the component definition.

First Look at Services and Dependency Injection

See sample 11. A1 — A2: Angular 1 Services and DI.

Your Skills Translate

Now for a recap: we’ve quickly covered 7 concepts which are different in Angular 2.

John explains that many other Angular 1 concepts remain the same in Angular 2: Modules, Filters/Pipes, Routing, HTTP, Events, and Promises.

Putting it All in Context of an App

We see that these different Angular concepts are brought together in a Star Wars: The Force Awakens Story Tracker application.

Angular 2 Resources

John discusses the Angular 2 Cheat sheet and the Tour of Heros tutorial and wraps up the module.

Angular 2 Essentials: Modules, Components, Templates, and Metadata

Modules

John begins with the ravoli metaphor, introducing the concept of modules. John explains that ES6/ES2015 (the latest version of JavaScript) did not exist when Angular 1 was written so it had to have its own custom modules solution.

Fortunately Angular 2 uses the standard ES2015 modules.

Components

“A component contains application logic that controls a region of the user interface that we call a view.”

John explains that while in Angular 1 we had a Controller and a Template and usually linked through a router, in Angular 2 a Component identifies its Template right way.

Defining a Component

Scroll down to 13: A2 Components and look at the <my-character> element in index.html

The content from this element comes from our component class app/character.component.ts

See that this component’s settings specify

selector: ‘my-character’
templateUrl: ‘app/character.component.html’

The object that defines these properties is called the component decorator.

The selector maps to the index.html element tag name. The templateUrl maps to our view file.

John updates, breaks and fixes this code to demonstrate how this works. We see that main.ts must also reference the character component. We also learn that it is essential to export our component class.

Templates

“Templates are the View

They are mostly HTML, with a little help from Angular. They tell Angular how to render the component.”

In this clip we see some things that a Template can contain or reference:

  • Directives, e.g. *ngFor or *ngIf
  • Interpolation, e.g. {{vehicle.name}}
  • Nested Components e.g. <vehicle *ngIf=”selectedVehicle” [vehicle]=”selectedVehicle”></vehicle>

John illustrates an example component tree that we can create.

Nesting Components

Scroll down to 14. A2: Nested Components to follow along with this demo.

We learn the importance of importing and defining directives for your custom components here.

Metadata

John shows us some of the common settings that we can specify in our @Component decorator.

Examining the Parts of a Component

In this clip John briefly describes the component:

  • Decorators
  • Template and Styles
  • Directives
  • Providers
  • Injectors
  • Output
  • Emit Events
  • Input
  • Actions

Component Communication with Input and Output

“Components allow input properties to flow in, while output events allow a child Component to communicate with a parent Component.”

We see an example output property and code to emit the output.

Scroll down to 15: A2: Input/Output Components to view the sample code.

Parent to Child Communication with ViewChild

This clip introduces the ViewChild decorator.

No scrolling down required this time, just view 0. Angular 2 Storyline Tracker, which is the application that brings everything together.

John demonstrates the Filtering and some other functionality that this app provides.

In Plunker, click on app/vehicles/vehicle-list-component.ts to see the ViewChild.

Displaying Data: Data Binding, Directives, and Pipes

Data Binding

We learned in the previous module that there are four ways to do data binding.

Here we see a reminder of this, and learn a bit about ngModel, which is shown here as a banana in a box.

John explains that, unlike Angular 1, Angular 2’s change detection is based on unidirectional data flow, e.g. either from a template to a component, or vice versa but not both. This results in many benefits over Angular 1:

  • Easier widget integration
  • No more $apply
  • No more repeated digest cycles
  • No more watchers
  • No more performance issues with digest cycle and watcher limits

Interpolation

Scroll down to 16. A2: Data Binding and Directives

John shows us character.component.ts and the template character.component.html, and demonstrates how to using interpolation to create image links.

Property Binding

John explains that property binding is always one way, and that we do this using the square bracket [] notation.

Adding Property Binding

Here we see the property binding can achieve the same functionality as interpolation, as John updates the image link example.

In this clip, John uses some materials design light CSS classes. If this is not familiar to you, you may want to watch Building a Web Application with Polymer.js and Material Design.

With Polymer and Material Design, you get many of the advantages of Angular without using a heavy framework.

Also in this clip John mentions ARIA. If this is not familiar to you, you can learn more about it in Web Accessibility: Getting Started

Event Binding

We want to make our app more interactive, and we use Event binding for this.

Event binding uses the round brackets () notation to send events from the Template to the Component.

John discusses custom events and the role of the EventEmitter.

Adding Event Binding

This example demonstrates updates on mouseenter and mouseleave events.

We see that we can do Two Way Binding by using event binding together with property binding, but the code is very verbose.

Two Way Binding

Put one of these in a box

We’re back to boxes and bananas again with the [()] notation.

[(ngModel)] = “expression”
bindon-ngModel=”expression”

This is a shorthand syntax for the functionality implemented in the previous clip.

Built-in Directives

“When Angular renders templates, it transforms the DOM according to instructions from Directives”

John shows us some Angular 1 directives and the new syntax for their equivalents in Angular 2.

In general, you just remove the hyphen and use camel case.

For example ng-class is now ngClass.

One or two directives have been renamed. ng-repeat is now *ngFor.

All structural directives begin with an * to mean we are changing something in the DOM.

Adding Attribute and Structural Directives

John demonstrates the above concepts in Plunker.

Pipes

“Pipes allow us to transform data for display in a Template.”

In Angular 1 these were called filters. They use the pipe character: |

Examples of pipes include Date pipes, Numeric pipes and Async pipes.

Async pipes subscribe to a Promise or an Observable, returning the latest value emitted.

To learn about promises in ES2015 see the promises chapter in exploring JS.

We can also create our own pipes, and John shows an example of this.

For full details, see Angular.io’s Pipes documentation.

Exploring Template Syntax in Storyline Tracker

View the full sample 0. Angular 2 Storyline Tracker, and start with the code in app/vehicles/vehicle-list-component.ts

Services, Dependency Injection, and Component Lifecycle Hooks

Services

“A Service provides anything our application needs. It often shares data or functions between other Angular features”

John explains that in Angular 1 we are forced to learn five separate but highly related concepts:

  • Factories
  • Services
  • Providers
  • Constants
  • Values

In Angular 2 we just have a class. A service is just a JavaScript class.

Refactoring for Services

Scroll down to 17. A2: Need Services — in this sample we have hard-coded data, and our task is to refactor it so that we instead fetch this data from a service.

Dependency Injection

“Dependency Injection is how we provide an instance of a class to another Angular feature”

We see how to do this by putting our service into our constructor.

We see Angular 1 and 2 implementations side by side. $inject is no longer used in Angular 2. However we now have @Injectable() which is similar to the old $inject and provides metadata about the Injectables.

Registering Services with the Angular Injector

We see a side by side comparison of registering services in Angular 1 and 2.

John recommends registering your services with the injector at the parent that contains all components that require the service.

Be careful not to accidentally register your service twice, because you won’t get an error if you do.

Component Lifecycle Hooks

“Lifecycle Hooks allow us to tap into specific moments in the application lifecycle to perform logic.”

John shows OnInit as an example and explains why this is a good idea even though it is not strictly required.

John also introduces us to events in a component lifecycle:

  • ngOnChanges
  • ngOnInit
  • ngAfterViewInit
  • ngOnChanges
  • ngOnDestroy

For further details see Angular.io’s Lifecycle Hooks documentation

Inspecting Lifecycle Hooks

See 19. A2: Component Lifecycle Hooks

Look at the Lifecycle Hooks in app/character.component.ts

John explains that these hooks enable editors like Visual Studio Code to warn you about typos.

Services, DI and Hooks in Storyline Tracker

We go back to our full application sample Storyline Tracker to see how Services, DI and Hooks apply in a more real world application.

Data with HTTP

HTTP

“We use HTTP to get and save data with Promises and Observables. We isolate the http calls in a shared Service.”

We see another side by side comparison of both versions of Angular, and learn that HTTP is in a separate module.

John mentions that some browsers support the fetch protocol, and we could use that, but for now we reference http.dev.js and use the ‘angular2/http’ module.

John explains how to do this step by step.

Using HTTP in Angular

We now at sample 20. A2: Needs HTTP and in index.html you can see we already have a reference to http.dev.js

In app/app.component.ts, John adds HTTP_PROVIDERS into the providers array and imports HTTP_PROVIDERS from ‘angular2/http’.

Now look at app/vehicle.services.ts. Here John adds a constructor of type Http, and this type, aand also the Response type, is imported from ‘angular2/http’.

The data is found at vehicles.json and John shows us how to process this with TypeScript code.

Adding Exception Handling for HTTP

In app/vehicle.services.ts, John adds a catch, which calls our new handleError method.

handleError uses an Observable, which means we need to import Observable from ‘rxjs/Rx’

John encourages you to look at the RxJS library to learn more.

RxJs

“RxJs (Reactive JS) implements the asynchronous observable pattern and is widely used in Angular 2”

RxJs is a large library and John suggests that while you import all of it for learning how it works, before you release into production, change you import statement to only import the modules that you require.

John describes Observables. They are an implementation of the Observer pattern.

You can learn more about the Observer pattern in the context of JavaScript in the final module of Jonathan Mill’s Practical Design Patterns in JavaScript.

We see a code snippet for returning from Http, and John explains that this allows us to do exception handling like we saw in the previous clip.

Async Pipe

“The Async Pipe receives a Promise or Observable as input and subscribes to the input, eventually emitting the value(s) as changes arrive.”

Here we see code using Observable properties, and John explains that the component code is now simplified.

Applying the async pipe in the template is even easier: just add:

| async

Adding an Async Pipe with an Observable

Scroll down to 21. A2: Http. John takes this code and modifies it to use async.

This only takes a minute. See the finished version at 22. A2: Http with Async Pipe

Promises with Http

We look at an additional method from RxJS: toPromise()

Http in the Storyline Tracker

We go back to our full application sample Storyline Tracker to see how HTTP works in our Star Wars inspired app.

Putting it All Together

Routing

Routing Essentials

“Routing allows our application to navigate between different Components, passing parameters where needed”

We see another side by side Angular 1 vs 2 example.

$routeProvider is out, @RouteConfig is in.

<ng-view> is out, <router-outlet> is in

John explains these and several other changes.

Routing is in a separate module, and you need to add a reference to router.dev.js

John describes all four steps necessary for adding routing to your application.

Adding Routing to an App

Scroll down to 24. A2: Needs Router.

John demonstrates each of the steps that he previously described, adding routing to the application.

Adding Routing and Navigation Links

John demonstrates how to use the router to add navigation to our app.

The resulting code can be found at 25. A2: Router.

Child Routers

“A Component may define routes for other Components. This creates a series of hierarchical child routes.”

We can define a child route with … notation, and in this clip we see a code example of this.

We look at snippets from both app.component.ts and vehicles.component.ts

Examining Child Routers

Scroll down to 26. A2: Child Router.

John explains all of this code for you here.

Routing in the Storyline Tracker

We’re almost at the end of the course. View 0. A2: Storyline Tracker.

John explains the code added for the routing and navigation in this application.

Course Verdict

At the time of writing Angular 2 Fundamentals has not been released.

This means Pluralsight subscribers wanting to learn Angular 2 have a choice of two courses, this and Angular 2: Getting Started, which I have previously watched and reviewed.

I thought that this First Look course might be a bit out of date, because it was based on the earlier Beta version 3 of Angular 2.

However, there haven’t been any major changes in the last few months and all of the information in this course applies as much as ever.

At the time of writing John Papa’s samples reference Angular 2 Beta 15, and he is regularly updating it.

The Getting Started course is a lot longer than this one (more than an hour longer), but I found the important concepts covered were the same.

In this First Look course, I found it very easy to understand the key concepts very quickly.

John Papa has done a great job of taking a big topic, breaking it down into the individual elements that you need to know, and explaining it simply.

Those of you who have no previous knowledge or interest in Angular 1 might feel more comfortable with the Getting Started course, which does not keep comparing and contrasting the different versions.

But if you want to learn the benefits that Angular 2 has over Angular 1, I recommend starting with this course, and then try writing your own small app in Angular 2.

Then if you are finding it difficult, watch the Getting Started course which will provide you with a lot of additional guidance.

Also read my review to see the sections that will be of most interest to you.

--

--

Kevin O'Shaughnessy

Sr. Full Stack Web Dev promoting better professional practices, tools, solutions & helping others.