Category: angular

AngularJS 1.5 Input Components

Introduction

The promise of JavaScript component-based architecture frameworks such as AngularJS 1.5, Angular 2, or Aurelia is enabling developers to write less code, both HTML markup, and JavaScript.  The ability to encapsulate HTML and JavaScript into reusable components should simplify the application consuming these components greatly.

Please, review this post and code, and then start your own component library for your applications. There are enough components here to get you started.  I have chosen to make these components granular with a single responsibility, rather that make a single component with many properties to change the behavior. This approach provides clean and readable HTML markup, clearly describing the components role and behavior.

This blog post and GitHub repo are written using ES6. I wrote why I use ES6 JavaScript here. I also leverage ES7 experimental class property features in my applications.

AngularJS 1.5 components are uncomplicated element directives. These components can encapsulate business logic and are testable.

If you have time, compare the amount of JavaScript code is required by Angular 2 components to the AngularJS 1.5 components. You’ll find that AngularJS 1.5 is simpler and currently requires considerably less framework code to register. You’ll also see that I separate the component registration from the component, this removes Angular from the component enabling very fast executing unit tests.  See the Review Presentation repo example.

The below images show the clean and minimal HTML required to produce a typical data form with comprehensive validation and associated messages, including password strength metrics. The “match” directive (see app.module.js) on the second input-password component handles comparing the two passwords. The corresponding error message is displayed below these components. The input control placeholder is included for instructional purposes only and is probably not needed in a simple form like this one.

html

form

References

I did my research before embarking on creating these input components. I’m very grateful to the many community authors for their blog posts and answers on StackOverflow. The below links helped me to understand this problem space and I recommend that you study them:

Creating a custom form field with validation using AngularJS 1.5 and TypeScript

Password Strength Meter

InputBaseComponent

The InputBaseComponent is the base class for the text input components. It exposes properties common to all HTML text input controls.

The InputBaseComponent creates the component label from the name attribute if the label attribute is not supplied. It’s onInit, onChange, and validate methods are invoked by deriving classes.

Normally an AngularJS 1.5 component does not update it’s parent model directly. As explained in the above blog post this component design calls for updating the model instead of using two-way bindings or a one-way binding with a corresponding event.

I agree with this architecture in this specific use case because it mimics the interaction that an input control would have if it was not encapsulated in a separate component. It is assumed that the form these components are hosted on would be adhering to the typical AngularJS component design pattern described in the AngularJS documentation.

By requiring the model in the component registration (see input-components.module.js), the model will be injected and is available to the component controller for reading and writing. When the view needs to be updated, $render is invoked and the below function updates the component value. When the component value is changed, the model value is set in the onChanage method.

COMPONENT REGISTRATION: 
require: {
    model: "ngModel"
}

ONINIT:
this.model.$render = () => {
  this.value = this.model.$viewValue;
}

ONCHANGE:
this.model.$setViewValue(this.value);

This base class handles setting sane values for the maximumLength and for setting  isRequired based on the minimumLength. The isRequired property is used in the HTML to set a required attribute.

The onChange method provides data input length validation by limiting the value length to the maximumLength.  This code is wrapped in try-catch block to provide a seam for logging an obvious attempt to hack your site. Remember, always defend in layers and never trust any data from the internet either on the client or server.

The validate method checks the input for minimum or maximum length validation rule violations. What is nice about this implementation is that the validation messages can easily be customized to provide the user with good information.  In this application, I’ve chosen to display the validation message next to the label.  If you don’t do this, then be sure to include the label in your validation message.

export default class InputBaseComponent {

  label;
  model;
  value;
  name;
  validationError;
  minimumLength;
  maximumLength;
  isRequired = false;

  constructor(StringUtility) {
    this.StringUtility = StringUtility;
    if(this.name && !this.label) {
      this.label = this.StringUtility.parseWords(this.name);
    }
  }

  onInit() {
    this.model.$render = () => {
      this.value = this.model.$viewValue;
    }
    if(!this.maximumLength) {
      this.maximumLength = 200;
    }
    if(this.minimumLength) {
      this.isRequired = true;
    }
  }

  onChange() {
    try {
      if(this.value && this.maximumLength && 
          this.value.length > this.maximumLength) {
        this.value = this.value.substring(0, this.maximumLength);
      }
    } catch(e) {
      this.value = '';
      // log this to your system as a security message
    }
    this.model.$setViewValue(this.value);
  }

  validate() {
    if(this.isRequired && this.minimumLength) {
      if(!this.value || this.value.length < this.minimumLength) {
        this.validationError = `has a minium length of ${this.minimumLength}`;
        return false;
      }
    }
    if(this.value && this.maximumLength && 
        this.value.length > this.maximumLength) {
      this.validationError = `has a maximum length of ${this.maximumLength}`;
      // log this to your system as a security message
      return false;
    }

    this.validationError = '';
    return true;
  }

}

InputBaseComponent.$inject = ['StringUtility'];

InputTextComponent

Now that we have all the hard work done, let’s extend InputBase and call the required methods.  For an input of type text, no additional validation is required.

import InputBase from '../input-base'

export default class InputTextComponent extends InputBase {

  constructor(StringUtility) {
    super(StringUtility);
  }

  $onInit() {
    super.onInit();
    super.validate();
  }

  onChange() {
    super.onChange();
    super.validate();
  }
}

InputTextComponent.$inject = ['StringUtility'];

InputEmailComponent

The InputEmailComponent extends the InputBase and adds email input validation. Notice that if the call to super validate returns false, this validation does not run.  You can change this logic to display all validation errors or display them one at a time as I do.

import InputBase from '../input-base'

export default class InputEmailComponent extends InputBase {

  constructor(StringUtility) {
    super(StringUtility);
  }

  $onInit() {
    super.onInit();
    this.validate();
  }

  onChange() {
    super.onChange();
    this.validate();
  }

  validate(){
    if(super.validate()) {
      if(this.value && 
          !this.StringUtility.isEmailValid(this.value)) {
        this.validationError = ' has invalid format';
        return;
      }
    }
  }
}

InputEmailComponent.$inject = ['StringUtility'];

InputTextComponent Template

This template has four groups:

  • input-group – apply CSS styles for spacing and alignment
  • form – subform container for the component
  • label-area – displays the label and associated validation messages
  • input – the input control

The validation messages are shown when:

  • the form control is invalid
  • and validation error text has a value
  • and
    • the control has been touched
    • or parent form has been submitted

You can choose when users see validation messages. I’ve used the above logic in my applications and users are happy with the experience.

<input-group>
  <ng-form name="{{vm.name}}Form">
    <label-area>
      <label for="{{vm.name}}">{{vm.label}}</label>
      <error-message ng-show="{{vm.name}}Form.{{vm.name}}.$invalid && 
        vm.validationError && 
        ({{vm.name}}Form.{{vm.name}}.$touched || 
        {{vm.name}}Form.$$parentForm.$submitted)">
          {{vm.validationError}}</error-message>
    </label-area>
    <input
      type="text"
      placeholder="{{vm.label | lowercase}}"
      autocomplete="off"
      ng-model-options="{allowInvalid: true, debounce: 250}"
      name="{{vm.name}}"
      id="{{vm.name}}"
      ng-model="vm.value"
      ng-change="vm.onChange()"
      ng-required="vm.isRequired"
      ng-minlength="vm.minimumLength"
      ng-maxlength="vm.maximumLength"
      maxlength="{{vm.maximumLength}}"
      >
    </input>
  </ng-form>
</input-group>

HTML Input Control

  • placeholder – optional.  I like, that I can bind the label and then use an Angular filter to change the label to lower case.
  • autocomplete – choose the option that meets your requirements
  • ng-model-options
    • allowInvalid – when true, allow ng-change to be raised on keystrokes when the control is invalid.
    • debounce – the time delay for model updating since the last keyboard input.
  • ng-model – binds to the component value
  • ng-change invokes the onChange method
  • ng-required – when true, sets the required attribute on the control
  • ng-minlength – sets the minimum length rule for the control
  • ng-maxlength – sets the maximum length rule for the control
  • maxlength – I STRONGLY urge you to ALWAYS set this attribute on any text input control.  Setting this attribute limits the number of characters that can be entered, pasted or dragged into the control at runtime. Remember that security is always in layers.

Form Submit Button Options

There are two schools of thought around form submit buttons.  One is to disable the submit button when the form is invalid, the other to allow the user to click the submit button and then show all input validation messages.

Your choice will depend on the application requirements and stakeholder choices.

The submit button strategy needs to take into account the applications timing of when to render validation messages.

I prefer to only show validation messages after the user visits the control or when the user submits the form and the control is invalid.

Thoughts

Whether you’re using AngularJS 1.5, Angular 2, Aurelia, et al., components provide the HTML and JavaScript developer a powerful programming paradigm that embraces separation of concerns, test ability, maintainability, readability, and are down right fun to work with.

Download

https://github.com/Oceanware/InputComponents

Close

Have a great day,

Just a grain of sand on the world’s beaches

Component Generator for AngularJS, Angular 2, Aurelia​

Introduction

I believe developers should own their code generation story. The value in owning your code generation is that when platforms change, APIs change, language grammar is enhanced, you can easily refactor your templates and not miss a beat. I also believe that owning your code generation story is a forcing function for thinking out how your application works, is wired up, and how to unit test it.

This tool provides templates that you must edit before generating any code.

What?  No ready-made templates?  Karl, are you nuts?  Why?

Let’s think about code generation templates for a minute. Templates are used to create language specific output.  Developers are using many flavors of JavaScript today: ES5, ES6, ES6 with ES7 experimental features, TypeScript, Coffee Script, etc. Stylesheet files can be written using LESS, SASS, SCSS, or CSS.

What language should I use to write the templates?  I use ES6, but not everyone does.

Let’s think about how Angular apps are structured and wired up.  Check ten blog posts, and you’ll read about ten valid ways to structure and wire up an Angular SPA app.

Small apps are wired up differently than medium or large apps.  Some put small modules in a single folder, whereas a medium-sized module may be within a single parent folder, with each component in a separate folder.

Developers doing unit testing will structure their component wire up differently to better support testing scenarios without having to load Angular for a component or controller unit test.  Not loading Angular for each unit test significantly speeds up your unit tests.

Based on the above language, structure, and wire up options, providing default templates would provide zero value.

Your Small Part

You’ll edit the empty template files for the component based SPA frameworks you author applications for such as AngularJS, Angular 2, or Aurelia. Having you edit your templates provides the best solution for this tool supporting many different: JavaScript flavors, AngularJS coding styles, and component wiring up strategies. Additionally, you’ll be the proud owner of your code generation story.

This tool uses Underscorejs templates that are easy to author, usually requiring a minute or two. However, if your scenario requires it, you can swap out the template engine.

More Than a Tool

My first version of this tool was written in less than two hours as single ES6 file and worked great. It didn’t have any tests but worked perfectly for my one scenario which was, Angular 1.5.9 components and ES6.

Then my mentoring and scope creep genes kicked into high gear, and I spent a few days and several versions to produce this tool.

I didn’t want to miss an opportunity to share a tool that I think will benefit many developers across languages, SPA frameworks, and scenarios. But to accomplish this goal, the tool would require 100% test coverage, work for any JavaScript language and any SPA component based framework.

I hope that others can learn from the architecture, code, and unit tests presented here. I welcome both positive and negative feedback to improve the tool and code.

This tool was also a forcing function for me to dive deep into authoring testable Node.js tools using ES6. It took me a little time, learning the testing tools, but when I refactored the code, having 100% test coverage paid off in spades.

Background

During my career as a Software Engineer and Architect, I’ve always written tools to increase my productivity and accuracy. Tools like XAML Power Toys or this tool came about because I found myself repeating the same task over again, and knew the computer is capable of making me infinitely more productive.

Two weeks ago I started writing an AngularJS 1.5.9 component based application.  AngularJS components are similar in concept to Angular 2 and Aurelia components although the syntax and implementation are a little different.

After creating my second component, I stopped to write this tool. I’m not going to perform mundane, repetitive tasks like creating: folders, components, controllers, templates, tests, and CSS files; this is a perfect assignment for a tool.

In addition to creating folders and files, the tool leverages user editable templates for generating code that matches your requirements and coding style. The ability to generate boiler maker code yields a significant increase in productivity.

What You’ll Learn

  • Features of the tool
  • Tool Architecture
  • Requirements
  • Installation
  • Local development installation
  • Local production installation
  • Command line usage
  • Editing Templates

Videos

  • Getting Started
  • Modifying the tool
  • Unit testing the tool

Features

  • Node.js command line utility, written using ES6 and TDD methodology
  • Cross-platform Windows, Mac, and Linux (thanks to Node.js)
  • User editable templates drive the generated code
  • Create components for any JavaScript framework like AngularJS, Angular 2, and Aurelia
  • Separating templates by framework enables supporting multiple frameworks
  • Component output folder is optionally created based on a command line option
  • Component controller file is optionally generated based on a command line option
  • Component unit test file is optionally generated based on a command line option
  • Component CSS file is optionally generated based on a command line option
  • You can modify anything about this tool, make it fit like a glove for your workflow

Tool Architecture

This object-oriented application tool was written using ES6. I have separated the functionality of the application into small single-responsibility classes. Besides good application design, it makes understanding and unit testing much easier. When I think of this tool, a .NET Console application immediately comes to mind.

I wrote Guard clauses for every constructor and method. I always add guard clauses, even on private methods, irrespective of language because I am a defensive software engineer. Writing guard clauses requires no extra effort given tools like Resharper and the ubiquitous code snippet feature in most editors and IDEs. Guard clauses future proof code in maintenance mode when another developer makes a false assumption while editing, next think you know a customer is filing a bug.

In some of the classes, I have refactored small sections of code into a method. Doing this makes the code easier to read, comprehend, and simplifies unit testing.

Classes

  • ApplicationError – deriving from Error, an instance of this class is thrown when a user error caused by improper command line usage occurs. It permits the top-level try catch block in the ComponentCreator to perform custom handling of the error.
  • CommandLineArgsUtility – provides functions related to command line arguments.
  • ComponentCreator – performs validation and writes the templates.
  • IoUtility – wrapper around Node.js fs.
  • Logger – wrapper around Console
  • TemplateItem – wrapper around a supported framework, exposes all data as immutable
  • Templates – stores collection of TemplateItems, provides immutable data about code generation templates.

The entry point for the tool is index.js.  This module instantiates a TemplateItem for each supported framework, creates all of the required dependencies for the ComponentCreator and injects them, then invokes the create method on the ComponentCreator instance.

The reason for creating and injecting all external dependencies in the root of the application is to enable unit testing. Dependencies injected using constructor injection can easily be stubbed or mocked.

I have successfully used this type of architecture for writing other complicated Node.js applications.

Dependencies

  • Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.
  • Chai – is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
  • Istanbul – full featured code coverage tool for Javascript
  • Mocha – is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.
  • Sinon.js – Standalone test spies, stubs, and mocks for JavaScript.
    No dependencies and works with any unit testing framework.
  • Sinon-Chai – provides a set of custom assertions for using the Sinon.JS spy, stub, and mocking framework with the Chai assertion library. You get all the benefits of Chai with all the powerful tools of Sinon.JS.

Requirements

  • Node.js  (install either LTS or Current versions.  Personally I use the Current version.)

On Mac’s I don’t recommend installing Node.js from the Node.js website. If you do, upgrading is a PIA.

For Mac users, use brew. After installing brew, run this command from a terminal:

brew install node

If you use brew, future upgrading or uninstalling Node.js on your Mac is a breeze.

Recommendations

To help understand how this application is setup and how unit testing is setup and invoked, please read my blog post: https://oceanware.wordpress.com/2016/08/10/easy-tdd-setup-for-nodejs-es6-mocha-chai-istanbul/

Installation

Ensure you have installed above requirements.

Download or clone the Component Generator repository here.

Open a terminal or command window, and then navigate to the root folder of the tool and run this command.

npm install

Next, run the unit tests and see the coverage report by executing this command:

npm test

Running the unit test also runs the Istanbul code coverage tool which outputs a detailed coverage report in the /coverage/lcov-report/index.html file.

Local Development Installation

During development, testing, and editing of your Node.js command line tools you’ll need to set up a symbolic link so you can execute your tool from any folder. Setting up a symbolic link instead of installing your Node.js package globally, allows you to continue editing the tool’s code, while at the same time, being able to execute the tool from any folder on your computer.

Mac and Linux

From the root folder of the tool, open a terminal or command window and run this command:

npm link

To test you development installation run this command:

gencomponent

The tool will display the command line usage.

Navigate to another folder and rerun the gencomponent command.  You should get the same output.

Windows

You MUST give yourself Full Permissions on the /node_modules folder before proceeding.

Follow the above steps for Mac and Linux.

Local Production Installation

This step is optional.  If you like the convenience of being able to edit your templates or change the tools code, while at the same time being able to invoke the tool from any folder then, by all means, skip this step.

If you want to install the tool globally, or want to install the tool on other machines, then follow these steps.

Before proceeding, you need to remove the symbolic link you created in the above steps.

Navigate to the root folder of the tool, open a terminal or command window and run the following command:

npm unlink
Window, Mac, and Linux

Navigate to the root folder of the tool, open a terminal or command window and run the following command:

npm install -g

You can now invoke the tool from anywhere on your machine.

After installation, if you need to modify the tool or template, uninstall the tool globally, make the changes and reinstall it globally.

Command Line Usage

Before proceeding, ensure you have created a symbolic link for the tool, or installed it globally.

gencomponent (component name) [-(framework)] [--ftsc]

The component name is required to generate a component.

The framework is optional and defaults to ‘ng’ if not supplied. Default framework can be changed by modifying the code.  Default valid options:

  • -ng
  • -ng2
  • -aurelia

Code generation options are prefaced with a double dash  (–), are optional, and can be in any order. The valid options are:

  • f = create a component folder
  • t = create a component unit test file and controller unit test file for the optional controller
  • s = create a component CSS file
  • c  = create a component controller file

If invalid arguments are provided or you attempt to create a component that already exists, an error message will be displayed at the command line.

Usage Examples

1. Show the command line usage message.

gencomponent

gencomponent ?

2. Create the Sales component in the current folder along with the sales.component js, and sales.template.html files. Templates are selected from the default /templates/ng folder.

gencomponent Sales

3. Create the Sales component in a new component folder named Sales along with the sales.component js, sales.controller.js, sales.template.html, sales.component.spec.js, sales.controller.spec.js, and sales.template.css files.  Templates are selected from the default /templates/ng folder.

gencomponent Sales --ftcs

4. Create the Sales component in the current folder along with the sales.component js, sales.component.spec.js, and sales.template.html files. The templates are selected from the /templates/aurelia folder.

gencomponent Sales -aurelia --t

5. Create the SalesDetail component in a new component folder named SalesDetail along with the salesDetail.component.js, salesDetail.component.spec.js, salesDetail.controller.js, salesDetail.controller.spec.js, and salesDetail.template.html files. The templates are selected from the /templates/ng2 folder.

gencomponent SalesDetail -ng2 --ftc

You can easily modify this tool to handle more or less supported frameworks and change the file naming conventions.

Editing Templates

Please read Underscorejs template documentation, it’s very short.

Template engines allow the template author to pass a data object to methods that resolve the template and produce the generated code.

This tool passes a rich data object that you can use inside your templates.

gencomponent SalesDetail

The below template data object was hydrated and passed to the template engine when the tool was invoked with SalesDetail as the desired component.

{ componentName: 'SalesDetail',
 componentSelector: 'sales-detail',
 componentImportName: 'salesDetail.component',
 controllerImportName: 'salesDetail.controller',
 componentImportNameEnding: '.component',
 controllerImportNameEnding: '.controller',
 templateFileNameEnding: '.component.html',
 componentFileNameEnding: '.component.js',
 controllerFileNameEnding: '.controller.js',
 componentSpecFileNameEnding: '.component.spec.js',
 templateCssFileNameEnding: '.component.css' }

This snippet from the below HTML file shows the syntax for injecting the componentName property value into the generated code.

<%= componentName %>

The below HTML can be found in the /temples/ng/componentTemplate.html file. This demonstrates consuming a data object property in a template.

<h2>Component Generator Data Object</h2>
<p>These are the data properties available in all template files.</p>
<p></p>
<p>componentName = <strong><%= componentName %></strong></p>
<p>componentSelector = <strong><%= componentSelector %></strong></p>
<p>componentImportName = <strong><%= componentImportName %></strong></p>
<p>controllerImportName = <strong><%= controllerImportName %></strong></p>
<p>componentImportNameEnding = <strong><%= componentImportNameEnding %></strong></p>
<p>controllerImportNameEnding = <strong><%= controllerImportNameEnding %></strong></p>
<p>templateFileNameEnding = <strong><%= templateFileNameEnding %></strong></p>
<p>componentFileNameEnding = <strong><%= componentFileNameEnding %></strong></p>
<p>controllerFileNameEnding = <strong><%= controllerFileNameEnding %></strong></p>
<p>componentSpecFileNameEnding = <strong><%= componentSpecFileNameEnding %></strong></p>
<p>templateCssFileNameEnding = <strong><%= templateCssFileNameEnding %></strong></p>

Template Folders

  • /ng – AngularJS
  • /ng2 – Angular 2
  • /aurelia – Aurelia

Available Templates

  • Component – always generated
  • Component Template – always generated
  • Controller – optionally generated
  • Component Unit Test – optionally generated
  • Controller Unit Test – automatically generated if the Controller and Component Unit Test is generated
  • Component Template Stylesheet – optionally generated

Workflow for Editing Templates

Before diving into template editing, you need to know exactly what the outputted generated code needs to look like.

You’ll need to decide on your application structure and wiring up.  Will you put your controllers inside the component file or keep them in separate files? Are you going to write unit tests?

I recommend, writing several components, w0rk out the details, identifying repeated code such as imports or require statements, and commonly used constructor injected objects.

In the below example, I have an existing About controller that represents how I would like my controllers to be generated.

Copy the code to generate into the appropriate template file, and then replace the non-repeating code with resolved values from the template data object.

In the below example, I copied the About controller into the componentTemplate.controller.js file and then replaced the “About” name with the componentName data object property.

class AboutController {
   constructor() {
   }
}

export default AboutController;

This below template will generate the above code.

class <%= componentName %>Controller {
    constructor() {
    }
}

export default <%= componentName %>Controller;

Now repeat the above steps for each template and for each framework you’ll be performing code generation.

Note that some templates will be empty, this is normal for .css and possibly .html files. But at least you didn’t have to waste precious time creating the file.

Videos

Getting Started

This 8-minute video explains how to get started with this tool.

Modifying the Tool

This 11-minute video explains how to modify:

  • templates
  • frameworks
  • file naming conventions
  • template engine

Unit Testing the Tool

This 23-minute video explains unit testing this tool.

Close

Writing your own cross-platform, command-line tools using Node.js is fun.

Having 100% test coverage is not easy and takes time. Just know that your customers and fellow developers will appreciate you putting the effort into a release with 100% test coverage.

Have a great day.

Just a grain of sand on the worlds beaches.

 

Angular 1.5.7 Components ES6 and jspm

Purpose

The purpose of the blog post and accompanying simple example project is to show you how to:

  • Create an ES6 Angular 1.5.7 super simple web application with navigation
  • Use Angular 1.5.7 Components
  • Use Angular Component Router  (not the constantly changing Angular 2 Router)
  • Bootstrap an ES6 Angular 1.5.7 application
  • Set up ES6 Angular 1.5.7 modules
  • Configure the Component Router
  • Provide a root component that hosts the entire application; providing a placeholder for the Component Router to navigate components into
  • Demonstrate writing super clean ES6 code that is 98% void of the word Angular.
  • Provides two Components that the app can navigate to.

This sounds like a lot, but it’s accomplish with only a few succinct ES6 files.

Background

I’m a total fan of Angular 1.x and now Angular 1.5.x after watching Scott Alan’s Pluralsight Course on Building Components with Angular 1.5.

I’m a fanatic about authoring my JavaScript using ES2015 (ES6, Harmony) and using jspm as my package manager.  This combination of language and package management is so clean and simple.

Scott’s course uses ES5.  Probably a good decision as it keeps the concept count down for Angular 1.x developers who still use ES5.

I highly recommend you watch the course; in about 90 minutes you’ll be another convert to using Angular 1.5.x Components.

I have looked at both Aurelia and Angular 2.  They are both still in beta and undergoing API and tooling changes. I’m very keen on Aurelia and am looking forward to adopting this product in the future.  What I like most about Aurelia is that the team embraced convention over configuration which dramatically reduces the boiler maker code for common scenarios.  Maybe Angular 2 will one day refactor their API to do the same.

Introduction

Authoring Angular 1.x or 1.5.x apps using ES6 with jspm is  simple and the code is very clean.  I have a project that demonstrates using Electron, Angular 1.x, ES6, and jspm. I will be creating a new project that uses Angular 1.5.7, Electron, ES6, and jspm very soon.

When using ES6 in today’s browsers or in Electron, the ES6 must be transpiled to ES5.  jspm hides all  that complexity and just does it for you. 

Gulp also has a module called gulp_jspm with an option, “selfExecutingBundle” that will essentially pre-compile, bundle, and minify all of your application’s ES6 to ES5.  Heck, it even removes all traces of ES6 libraries from the bundle.

Transpiling, bundling, and minification are part of “real world ES6 development.”  I just like that jspm makes this process simple and almost 100% transparent. 

Please note:  jspm is not the only game in town.  There are many other techniques, frameworks, build systems, etc., that accomplish the same task, producing the same end result.  When I did my study last year, I found that jspm worked best for me.  I recommend that you look at all the options and tools, read many blog posts on the subject just like I did. Then choose the one you understand and can be successful with.

Please note:  This application does not take any dependencies on the volatile and changing Angular 2 Beta.  The Component Router used in this project, is the original Angular 2 router and its works great.  I strongly recommend staying away from Angular 2 dependencies until the team has had time to ship RTM bits and ensure they have an approved, and good story for Angular 1.5.x integration.

Additionally, I have yet to see a compelling reason to write production code in Angular 2.  Like you, I have Angular 1.x projects in production and that run everyday and perform beautifully. 

Application Startup

Before you can run off and write the next awesome app using Angular 1.5.7 Components and ES6 we need to learn how the application starts up.  As you’ll see there are differences between the ES6 jspm code I’ll present and the current AngularJS 1.x ES5 apps you’re writing today.

index.html

  • Is loaded by the browser or Electron
  • Loads up system.js and config.js using script tags
  • The bootstrap.js module is imported.  The act of importing a module causes it to execute
  • Notice you don’t see any Angular framework markup as we will be manually bootstrapping Angular.

<!doctype html>

<html lang="en">
<
head>
<
meta charset="utf-8">
<
meta http-equiv="X-UA-Compatible" content="IE=edge">
<
meta name="viewport" content="width=device-width, initial-scale=1">

<title>Angular 1.5.7 Components ES6 jspm</title>
</
head>
<
body>
<
script src="src/jspm_packages/system.js"></script>
<
script src="src/config.js"></script>
<
script>
System.import('app/bootstrap').catch(console.error.bind(console));
</script>

<app-root></app-root>
</
body>
</
html>

bootstrap.js

  • framework dependencies are loaded
  • application ES6 modules are loaded
  • when the modules are all loaded and the document is ready, then bootstrap Angular
  • Notice how Angular is imported and provided a name, “AppModule”  I now have full access to my module and can access properties like, “name”
// load our framework modules
import angular from  'angular';
import 'ngcomponentrouter';

// load our application ES6 modules 
import AppModule from './app.module';
import './app-root.component';
import './About/app-about.component';
import './Home/app-home.component';

angular.element(document).ready(() => {
    // bootstrap angular now that all modules have been loaded
    angular.bootstrap(document, [AppModule.name], {strictDi: true});  
});

app.module.js

  • framework dependencies are imported so we can use them
  • Angular module named “app” is created and the Component Routers is injected as a dependency
  • Component Router root component is configured. Look back to index.html and you’ll see the app-root component in the markup
  • Export the Angular “app” module
import angular from  'angular';
import ngcomponentrouter from 'ngcomponentrouter';

let module = angular.module('app', [ngcomponentrouter]);

// must tell the Component Router which component to navigate components into
module.value('$routerRootComponent', 'appRoot');

export default module;

app-root-component.js

  • Import the above app.module default export, which is the angular.module(‘app’).  Consumers have clean code now.  Angular no longer appears in the code.
  • Register the ‘appRoot’ component with the AppModule and set its template.
  • Configure the root component router
  • Last line configures the default route
import AppModule from './app.module';

AppModule.component('appRoot', {
  templateUrl: '/src/app/app-root.component.html',
  $routeConfig: [
    { path: '/home', component: 'appHome', name: 'Home'},
    { path: '/about', component: 'appAbout', name: 'About'},
    { path: '/**', redirectTo: ['Home']}
  ]
});

app-root.component.html

  • This is my incredibly simple application root object.
  • It provides some navigation links for the Home and About components
  • The ng-outlet directive is where the Component Router will site components as they are navigated to.
<h1>Hello World</h1>

<p>
  <a href="#home">Home</a>
</p>
<p>
  <a href="#about">About</a>
</p>

<ng-outlet></ng-outlet>

app-home.Component.js

  • Import the app.module
  • Register the ‘appHome’ component with the AppModule and set its template.
  • See how clean this code is?
import AppModule from '../app.module';

AppModule.component('appHome', {
  templateUrl: '/src/app/Home/app-home.component.html'
  });

Download

Make sure you have node.js and jspm installed globally.

You can download or clone the simple repro here: https://github.com/Oceanware/ng157es6jspm

After downloading or cloning, navigate to the folder and open a command prompt (terminal window for OS X or Linux) and execute:

npm install

npm start

Your browser will open and display the application.

Close

You can start to see the simplicity of Angular 1.5.7 and ES6.  Clean JavaScript files, very easy to understand the intent of the code.  Fun programming!

Have fun and be productive with Angular 1.5.7 and ES6.

Hope this helps someone and have a great day.

Just a grain of sand on the worlds beaches.