My Angular 2 presentations for 2017

In 2017 I’m planning to speak at several conferences related to development of Web applications with the new Angular 2 framework. Below is the list of my presentations (each one is 90-min long). All of them can be delivered as a 2-day workshop in your organization.

Mastering TypeScript

TypeScript is a superset of JavaScript, which allows you to be more productive in writing JavaScript applications. The syntax of this language is pretty easy to pick up for anyone who’s familiar with such object-oriented languages as Java or C#. During this presentation you’ll learn the syntax of this language and will understand the benefits it brings to the table.

Make a facelift to your Angular 2 app with UI libraries

Commercial applications need to be good looking, which means that you should pick up a rich library of UI components for your app. While Angular Material library offers two dozen of great looking components, this may not be enough for your application needs. The good news is that there are other libraries that you can use. In this presentation we’ll start with an overview of Angular Material components. Then we’ll proceed with another open-source library called PrimeNG, which offers more than 70 UI components. Finally, we’ll review the code of an Angular 2 app that uses both Angular Material and PrimeNG components.

Angular 2 for Java developers

Angular 2 is a complete re-write of the super popular Web framework AngularJS. According to Pluralsight survey, Angular leads the list of what developers want to learn in 2016. Angular 2 is a component-based framework that will have an effect in JavaScript community similar to what Spring framework did for Java. This presentation is an overview of this hot framework, which in combination with TypeScript, finally made Web development understandable for Java developers. At the end of the presentation you’ll see a sample Web application written in Angular 2 on the front and Java on the server.

Angular 2: Working with the component router

In this session you’ll see how to use the router that comes with Angular 2 Final. We’ll start with configuring the navigation in a simple app. Then you’ll see how to pass data to routes, work child routes, and create apps with multiple router outlets (auxiliary routes). We’ll also review a unit-test configuration for testing router. Finally, you’ll see how how to lazy load modules using the router.

Angular 2: Communication with the server via HTTP and WebSocket protocols

In this session you’ll see how create an Angular 2 app that can communicate with the servers via a pull (HTTP) and push (WebSocket) modes. We’ll program a simple Node server and then will go through a number of code samples that communicate with it using HTTP and WebSocket protocols. We’ll start with creating a simple NodeJS server, and then will enable it to handle HTTP requests from an Angular 2 app. Then you’ll see how to wrap a service into an observable stream. Finally, we’ll teach our server to perform a data push to an Angular 2 client using the WebSocket protocol.

Implementing inter-component communication in Angular 2

Angular 2 is a component-based framework with a well-defined API for passing data to and getting data from a component. Any application is a tree of components that often need to communicate with each other.
In this presentation you’ll see how to create reusable application components that can exchange data with each other in a loosely-coupled manner. You’ll see how components can communicate via a common parent or via an injectable service. You’ll see how to pass data using component router, input and output parameters, events and callbacks. You’ll also learn how to use projection (formerly known as transclusion) to pass HTML fragments to a component’s template. We’ll also touch upon the incorporation of the third-party JavaScript libraries into an Angular 2 app.

Using Observable Streams in Angular 2

Angular 2 includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream.

Observables allow to introduce the push model to your application. First we’ll get familiar with the RxJS library, and then will continue reviewing observables in Angular 2. In this presentation you’ll see how to treat UI events, HTTP, and WebSocket connections as observable streams that push data. You’ll see how to wrap up any service into an observable stream so your application components can subscribe to it.

Angular 2 Tooling

Learning Angular 2 is easier than AngularJS, and developing in TypeScript is more productive than in JavaScript. But setting up the project and deploying the application is not straightforward. This presentation is not about the Angular 2 syntax. We’ll discuss the development process with Angular 2 starting from setting up the project to deploying an optimized application. We’ll start with discussing the Angular/TypeScript project structure and the proceed with such topics as using the module loader SystemJS, installing type definition files, bundling the app with Webpack and deployment in dev and prod. Finally, we’ll go through the process of scaffolding and bundling projects using the Angular CLI tool.

Angular CLI: Speed up installing dependencies with Yarn

Initially, the entry barrier into the world of Angular development was pretty high because of the need to learn and manually configure multiple tools. Even to get started with a simple application, you need to know and use the TypeScript language, the TypeScript compiler, ES6 modules, SystemJS, npm, and a development web server. To work on a real-world project, you also need to learn how to test and bundle your app.

To jumpstart the development process, the Angular team created a tool called Angular CLI (see https://github.com/angular/angular-cli), which is a command-line tool that covers all the stages of the Angular application lifecycle, from scaffolding and generating an initial app to generating boilerplate for your components, modules, services, and so on. The generated code also includes pre-configured files for unit tests and bundling with Webpack.

All this is good but a project generated by Angular CLI has a lot of dependencies that have to be downloaded and installed in the node_modules directory of your project. What’s “a lot”? Let’s use the Unix tree command to see how many files and directories exist in a project freshly generated by Angular CLI. Enter the following command in the root directory of such project:

tree node_modules

You’ll see a nicely formatted tree structure of all packages installed in the node_modules directory ai a summary line at the end, which will look like this:

6233 directories, 38656 files

This is what I mean by a lot. Actually all is relative. It clearly a lot if you compare with the content of node_modules of a jQuery project:

7 directories, 13 files

On the hand, the rumor has it that React Native installs 120K files. The software becomes more complicated every year and we have to deal with it. Anyway, Angular CLI has already created the project with all packages installed. Now, let’s delete the node_module dir in the project and reinstall it with npm install. On my laptop it takes at least 90 seconds. Can this time be improved? Yes, if you’ll use Yarn – an alternative to npm client.

Yarn is a new package manager that can be used instead of npm package manager. The plan is to use npm one last time to install Yarn, and then npm is not needed. Here’s the command to install Yarn globally:

npm install yarn -g

Now let’s run Yarn from within the root dir of our project:

yarn

This command reads (an equivalent of npm install) the list dependencies from your package.json file and installs all of them either from npmjs.org or from local cache. It takes anywhere from about one minute on the first run to install those 38K files. on the consecutive runs (after deleting node_modules) it takes 30 seconds. This is three times faster than npm! Pretty impressive.

To create a new Angular CLI project called sampleProj you can run the following command:

ng new sampleProj

The above command will generate the boilerplate code of the project in the directory sampleProj with package.json and will immediately run npm install there. On my MacBook Pro it takes at least 90 seconds. Now that we are fans of yarn, we’d like to integrate it in the initial project generation. This could be done in three steps:

1. Instruct Angular CLI to not run npm install:
ng new --skip-install sampleProj
2. cd sampleProj
3. yarn

If you use Mac or Unix-based OS, you can combine the above three steps as follows:

ng new --skip-install sampleProj && cd $_ && yarn

The bash parameter $_ refers to the last argument of the previous command, which is sampleProj in our case. Running the above command completes in 30 seconds, which is a lot better than 90, isn’t it?

For a regular non-CLI Angular project Yarn needs about 19 seconds on the first run and 12 seconds or less thereafter. On your computer, the results may be different.

Being more performant is not the only advantage of using Yarn over npm, and you can read more about Yarn’s architecture and benefits in Yarn blog. At the time of this writing, Yarn is still at its early stages, but you can start using it today.

UPDATE: As of Angular CLI Beta 31 you can simply set Yarn as your default package manager so Angular CLI will use it during generation of new projects:

ng set --global packageManager=yarn

I recorded the video showing how to do this.

Angular 2: Component communication with events vs callbacks

So a child component needs to pass some data to its parent. I use TypeScript and in this blog I’ll show you two techniques: events vs callbacks.

Emitting events

The technique with emitting events is well documented:

1. Declare a property of type EventEmitter and instantiate it
2. Mark it with an @Output annotation
3. Be nice. I mean use generics to make it obvious to other developer what are you emitting and let TypeScript compiler warn you it you’ll try me emit the object of the wrong type.

The next line shows you an example that implements all three steps in a component called PriceQuoterComponent, which will be emitting price quotes of type IPriceQuote.

@Output() lastPrice: EventEmitter <IPriceQuote> = 
                              new EventEmitter();

The above code is very declarative and easy to read even after I quit and will go to work for another company.

To actually emit/dispatch/fire the lastPrice event, you need to create an object of type IPriceQuote and invoke the function emit:

let priceQuote: IPriceQuote = {...};
this.lastPrice.emit(priceQuote);

Nice an clean. Our component is loosely coupled and reusable, because it has no strings attached to any other components. It just shoots the lastPrice event with a payload to whoever cares to listen (or subscribe) to this event. For example, a parent component can do it like this:

<price-quoter (lastPrice)="priceQuoteHandler($event)">
</price-quoter>

The event handler function is also very easy to understand, especially because its argument explicitly declares the type of the object its getting:

priceQuoteHandler(event:IPriceQuote) {...}

Callbacks

Not sure why do you even want to go this route. Most likely, because you’ve never been in the callback hell. Get ready to lose the goodness of explicit typing and be prepared to deal with the “this and that” problem. But if you insist, I’ll show you how to do it.

This time the child (PriceQuoterComponent) will declare an @Input property, which will accept the name of the callback function to be called on the parent. Remember the Hollywood principle “Don’t call me, I’ll call you”?

@Input() whoToCall: Function;

The parent will bind the name of its function to call. Now, the child instead of emitting the event will call that function on its parent:

let priceQuote: IPriceQuote = {...};

this.whoToCall(priceQuote);

The parent won’t be listening to child’s events because there won’t be any. But now the parent needs to do two things:

1. Declare and bind the function that has to be called by the child

2. Ensure that it’ll be invoked in the object that represents the parent and not on a global object. We need to pass the “this” object to the bound function, which can be done using arrow functions in ES6 or the function bind() in ES5:

@Component({
...
    template: `
   <price-quoter [whoToCall] ="fnPriceQuoteHandler">
   </price-quoter>`
})
class AppComponent {

    fnPriceQuoteHandler: Function;

    ngOnInit(){
        this.fnPriceQuoteHandler= 
              obj => this.priceQuoteHandler(obj); // ES6

        // this.fnPriceQuoteHandler=
        //     this.priceQuoteHandler.bind(this); // ES5
    }
}    

In this video I did a quick code overview of both implementations of the above components. The sources are here. I like the version with events better, and you?

Adding PrimeNG UI components to Angular CLI projects

Angular 2 CLI is a scaffolding tool and code generator that can be used for the real world projects. It saves you a lot of typing and spares you from worrying about config files for TypeScript compiler, testing frameworks, project bundler (it uses Webpack), and deployment.

PrimeNG is an excellent library of 70+ Angular 2 UI components. In this blog I’ll list the steps you need to perform to generate new project with Angular CLI and add PrimeNG library to this project.

If you don’t have Angular CLI installed yet, install it globally:

npm install @angular/cli -g

In the terminal window generate a new project, e.g. primeng_with_cli. Since I just want Angular CLI to generate only app compnent and module files, I’ll specify the option to generate inline template and styles and don’t bother with the test spec:


ng new primeng_with_cli --it --is --spec=false

Change to the newly created directory

 
cd primeng_with_cli

Add font awesome and PrimeNG as dependencies in package.json, e.g.


"font-awesome": "^4.6.3",

"primeng": "^1.0.0-beta.20",

Since the package.json was modified, install the above dependencies:

npm install

PrimeNG requires certain global styles so its components look pretty. Angular CLI projects have a config file angular-cli.json, where you can configure project settings, and in particular it has the property styles, which is the right place to add global style. Yes, I’m talking about the style tages that you’d add in the index.html in a regular Web app.

Angular CLI generate an empty file style.css and you need to add three more CSS file that are needed for PrimeNG:


"styles": [
    
  "styles.css",

  "../node_modules/primeng/resources/themes/omega/theme.css",

  "../node_modules/font-awesome/css/font-awesome.min.css",

  "../node_modules/primeng/resources/primeng.min.css"

] 

For sanity check run your new app by entering the following command in the terminal window:

ng serve

Open the app in the browser at 
http://localhost:4200, and Webpack dev server will happily render the single-page app with the text app works! This is a basic app that Angular CLI generated for you.

Now you need to modify the code in the generated dir app.component with the code that uses PrimeNG components. You can take the sample code from this blog. You’ll need to add required PrimeNG components to imports and declarations in the application module file app.module.ts.

The dev version of the app works, and now let’s see the prod version of this cool app. To prepare a production build run this command:

ng build --prod

Angular CLI will create bundles and will deploy all the files in the dist directory of your project. Take a peek into this directory and you’ll see the bundles that are available as .js files as well as their gzipped versions. The question is, how can we serve the existing gzipped files without having the web server do it for us? A simple solution is to install a static Node server that knows how to do it. Just add node-static package as dev dependency in package.json and install it:


"node-static": "^0.7.9" 
npm install

Finally, add the following npm script command in scripts section in package.json:



"serve:dist": "static dist -H '{\"Cache-Control\": \"no-cache, must-revalidate\"}' -z"

Start the static server and it’ll serve the optimized app on port 8080:



npm run serve:dist

NOTE: Creators of PrimeNG promised to add AoT support in the release candidate that will be available within a couple of weeks. When it’s done, you’ll be able to create smaller bundles by running this command:

ng build --prod --aot

That’s all folks!

PrimeNG – UI components for Angular 2

Angular 2 framework will become a complete platform for developing Web apps when it’ll offer a library of rich UI components. Angular Material 2 currently offers 16 UI components, which is not enough for commercial applications. Based on the current speed of development, it seems that Angular Material 2 will need another year to complete.

Meanwhile there are third-party libraries of UI components that you can use with your Angular 2 apps today. In this blog I’ll show you how to get started with the library called PrimeNG that already includes more than 60 UI components.

Java developers are familiar with the library PrimeFaces that is pretty popular for developing of the UI of JSF-based Web apps. PrimeNG is a port of this library for Angular 2 apps.

This library offers such components as Accordion, Panel, Grid, Dialog, Menu, charts, drag and drop, and many more. To see all PrimeNG components visit http://www.primefaces.org/primeng.

I’ve created a small seed project that can get you started in a minute. In this project I use three PrimeNG components: InputText, Button, and ConfirmDialog. Each PrimeNG component is offered as a module, and you need to add the required components to your @NgModule declaration, for example:

@NgModule({
    imports:      [ BrowserModule,
                    InputTextModule,
                    ButtonModule,
                    ConfirmDialogModule
    ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
})

Each component is well documented, and you can see the code snippets, properties, events handled by the component as well as try it in action. For example, check out the description of the ConfirmDialog component.

The library itself can be installed using npm from a command line or by adding the following line to package.json (I’ve used the Beta 17 version):

“primeng”: “^1.0.0-beta.17”,

The Release Candidate of PrimeNG should be available within a month.

To install and run this seed project, perform these steps:

1. Download and install Node.js from https://nodejs.org
2. Clone the repository https://github.com/yfain/primeng_seed into any directory and open it in the command prompt or terminal window.
3. Run npm install
4. Run npm start

The last command will start the app in your browser and you’ll see a window that looks like this:

primeng1

Enter your name and click on the button Greet me, and if your name is Yakov, you’ll see the following dialog window:

primeng2
If you like the look of this confirmation dialog click on the button Yes. The dialog window will go away and you’ll see the following:

primeng3

The entire code of the AppComponent that shows this window looks as follows:

import {Component} from '@angular/core';
import {ConfirmationService, Message} from "primeng/components/common/api";

@Component({
    selector: 'app',
    template: `<h1>Hello from PrimeNG!</h1>
               <input type="text" pInputText placeholder="Enter your name"
               (change)="onChangeEvent($event)" />
               <button pButton type="text" 
                    (click)="greetMe()" icon="fa-check" label="Greet me"></button>

               <p> {{theUserSaid}}
               
               <p-confirmDialog width="400"></p-confirmDialog>
              `,
    providers:  [ConfirmationService]
})
export class AppComponent {
    name: string;
    userResponse: Message[]=[];
    theUserSaid: string;

    constructor(private confirmationService: ConfirmationService) {}

    onChangeEvent({target}){
        this.name = target.value;
    }

    greetMe(){

        this.confirmationService.confirm({
            message: ` Hey ${this.name}, do you like PrimeNG?`,
            header: 'Greeting',
            icon: 'fa fa-question-circle',
            accept: () => {
                this.userResponse = [];
                this.userResponse.push({severity:'info', summary:'Confirmed', 
                                      detail:'I like PrimeNG'});
                this.theUserSaid = this.name + " responded " + 
                                     this.userResponse[0].detail;
            },
            reject: () => {
                this.userResponse = [];
                this.userResponse.push({severity:'info', summary:'Rejected', 
                      detail:'I don\'t really like PrimeNG'});
                this.theUserSaid = this.name + " responded " +
                          this.userResponse[0].detail;
            }
        });
    }
}

By the end of this month I’ll be flying to Romania to run my Angular 2 workshop for a private client, and they asked me to add a unit on PrimeNG. Will do.

Angular 2 training for your organization

If your team is interested in a hands-on, in-depth exploration of how to develop web applications with Angular 2, I can run a three day workshop in your organization. Participants will gain practical, skills while exploring the best practices and principles of developing Angular 2 applications and get familiar with multiple sample applications illustrating solutions for real-world challenges.

By the end of this live, hands-on course, participants will understand:

  • How to jump-start a new Angular project
  • How to arrange the client-side navigation in single-page applications
  • How to communicate with servers using HTTP and WebSocket protocols

And they’ll be able to:

  • Write code in TypeScript with the Angular 2 framework and deploy it in any modern web browser
  • Unit test the router, services, and components
  • Automate the building and deployment processes using the Webpack bundler and npm scripts

About your instructor

Yakov Fain is the coauthor of Angular 2 Development with TypeScript as well as a number of other technical books on programming. Yakov works as a software architect at the IT consultancy Farata Systems and develops software products for the insurance industry. A Java Champion, he has taught multiple classes and workshops on web and Java-related technologies, presented at international conferences, and published more than a thousand blog posts. Yakov lives in New York City.

What former clients say about Yakov’s Angular 2 workshops:

“The workshop is exactly what I have envisioned. The contents cover all of the critical and important aspects of the platform. It is also very hands-on. You made the training fun and engaging. The pace is also just right for impatient developers like us.”
– Emily Jeng, Princeton University

“I’ve attended several of your courses already. I think the plan and coverage are really comprehensive. I liked how we were going from a starter to the complete solution during the course and didn’t forget to talk about pros and cons and alternatives (several ways to build a form, SystemJS versus Webpack, etc.).”
— Dmitry N.

“Great class. Very thorough and great, detailed examples.”

— Coral S.

Prerequisites

Attendees must have basic knowledge of JavaScript and HTML. If you never worked with JavaScript before, please watch this video from one of the previous Yakov’s trainings. No knowledge of AngularJS 1.x is required.

Course outline

  • Unit 1. First steps with Angular 2
    • Introduction to Angular 2 architecture
    • Project structure and setup with npm
    • Brief introduction to TypeScript
    • Creating a “Hello World” app
    • Using the SystemJS loader
    • Templates and bindings
    • An overview of a sample Online Auction app
  • Unit 2. Client-side navigation and inter-component communications
    • Intro to client-side navigation with component router
    • Child routes, multiple router outlets, lazy loading of modules
    • How to install and use type definition files
    • Intercomponent communications
    • Implementing the mediator pattern
    • Projection of HTML fragments
  • Unit 3. Dependency injection and observable streams
    • Dependency injection
    • Providers and injectors
    • Promises (pull) versus Observables (push)
    • Observable events
    • Observable HTTP requests
    • Code review of the Online Auction
  • Unit 4. Working with Forms API and component life-cycle
    • Basic forms with ngModel
    • Template-driven forms
    • Model-driven forms
    • Form validation
    • The component life-cycle and hooks
    • How change detection works
  • Unit 5. Communicating with a server via the HTTP and WebSocket protocols
    • Creating a simple HTTP server with the Node.js and Express frameworks
    • Working with HTTP objects
    • Benefits of the WebSocket protocol over HTTP
    • Working with WebSockets
  • Unit 6. Unit testing and build automation
    • Unit testing with Jasmine
    • How to unit test Angular services, router, and components
    • Running tests with Karma
    • Getting familiar with the Webpack bundler
    • Working with Angular CLI

During this code participants performs many hands-on exercises. After each unit participants will spend half an hour working on a sample Online Auction app.

How to arrange this on-site training in your organization

This training is offered by Farata Systems, an IT consulting and training company. For training inquiries send an email at training @ faratasystems.com

Twenty one reason to use Angular 2 and TypeScript

Our company SuranceBay developed a platform for the insurance industry, and most of the UI for this system was written using Apache Flex framework (formerly Adobe Flex). Flex is an excellent framework for developing Web UI, but it requires Flash Player, which is not in favor anymore. Our quest for a good JavaScript framework started about four years ago.

After trying several pilot JavaScript projects we noticed a substantial drop in our developers’ productivity. A task that required one day in Flex would need three days in any JavaScript framework, including AngularJS. The main reasons were the lack of types in JavaScript, poor IDE support, and absence of compiler’s support.

When we learned that Google started development of the Angular 2 framework with TypeScript as a recommended language for development, we became early adopters. A year later we can confirm that the Angular 2/TypeScript duo is the most productive way of developing mid-to-large size Web applications that can run in any modern Web browser as well as on mobile platform.

These are the main reasons why I believe that Angular 2 and TypeScript are the right tools for developing Web applications:

1. The tooling support is as good as on Java or .Net platforms
2. TypeScipt code analyzer warns you about the errors as you type
3. Using TypeScript classes and interfaces makes the code more concise and easy to read and write
4. Clean separation between the code that renders UI and the code that implements application logic
5. The UI doesn’t have to be rendered in HTML, and there are already products supporting native UI rendering for iOS and Android
6. Angular 2 offers a simple mechanism for modularizing application with support of lazy loading of modules
7. The TypeScript compiler generates JavaScript that a human can read
8. The TypeScript code can be compiled into ES3, ES5, or ES6 versions of JavaScript
9. The router supports complex navigation scenarios in single-page applications
10. Dependency injection give you a clean way to implement loose coupling between components and services
11. Binding and events allows you to create reusable and loosely coupled components
12. Each component goes through a well-defined lifecycle, and hooks for intercepting important component events are available for application developers
13. Automatic (and fast) change detection mechanism spares you from the need to manually force UI updates while giving you a way to fine-tune this process
14. Angular 2 comes with the Rx.js library, which allows you to arrange a subscription-based processing of asynchronous data and eliminates the callback hell
15. Support of forms and custom validation is well designed
16. Unit and integration testing are well supported and you can integrate tests into your building process
17. The bundling and optimization of the code with Webpack (and its multiple plugins) makes the size of deployed application small
18. An ability to pre-compile the code eliminates the need to package Angular compiler (not to be confused with TypeScript compiler) with your app, which further minimizes the overhead of the framework
19. Angular Universal turns your app into HTML in an offline build step, that can be used for server-side rendering, which in turn greatly improves indexing by search engines and SEO
20. The library of the modern-looking UI components Angular Material 2 offers a number of modern looking components
21. The scaffolding and deployment tool (Angular CLI) spares developers from writing the boilerplate code and configuration scripts

From the management perspective, Angular 2 is appealing, because there are already more than a million AngularJS developers, and most of them will switch to Angular 2. Having a large pool of workers with specific skills is an important consideration for selecting a technology for new projects. Besides, there are more than 15 million Java and .Net developers combined, and many of them will find the syntax of TypeScript a lot more appealing than JavaScript, because of support of classes, interfaces, generics, annotations, class member variables, private/public variables, helpful compiler, and good support by familiar IDEs.

As you can see from this list, Angular 2 comes with batteries included. Check it out!