Posts

Angular 2.0.2 released – Guide on how to scaffold an app with Material2 using Angular CLI in minutes

Angular 2 is finally released and the tooling around it is maturing as well. In this screencast we use Angular CLI to scaffold an application from scratch, add routing to it and bootstrap material2 and finally steal the design from Jeremys sample app repo who’s on the material2 team. After recording this screencast I went ahead and upgraded the ng2play repo to the fully released version av angular2 (changelog 2.0.2).

Screencast

ng2 play @ github

As mentioned I decided to migrate the repo off screen since it would just be too messy and hard to follow along otherwise. For me it was actually easier to throw in my “old” components and services in a newly created application since a lot had changed, especially when moving to webpack.

Since we got inspired by Jeremys sample app we got two new themes in this screencast.

Light Theme

ng2light

Dark Theme

ng2dark

Material 2 Components Demo

I also decided to keep the material 2 components demo as a separate component in the app.
ng2material2

Sass Support

Since we’re using webpack now it’s super easy to compile sass files, all we needed to do was to add a line to angular-cli.json and restart the watch:

{
  "project": { ... },
  "apps": [
    {
      ...
      "styles": [
        "styles.css",
        "app-theme.scss"
      ],
      ...
    }
  ],
  "addons": [],
  "packages": [],
  "e2e": { ... },
  "test": { ... },
  "defaults": { ...}
}

Conclussion

Tooling is coming along really great with angular2 and in the screencast I scaffold an app according to best practices literally in matter of minutes, and the material2 team is producing some beautiful and well made components. Even though it’s nice to say that angular 2 is finally here it will be exciting to see what future versions of angular will bring us. They’ve just recently announced the versioning and releasing strategy for angular and may I say it’s pretty interesting.

Hope you’ve enjoyed the screencast, and as always have an excellent day!

Angular 2 RC 5 NgModules

Angular Modules, also known as NgModules, are the powerful new way to organize and bootstrap your Angular application. In this screencast we upgrade the ng2play repo to the latest release candidate (RC5).

Screencast

Links

Here are the links related to the screencast.

Migration Steps

We basically follow the migration steps in the guide, which are:

  1. Update to RC5: We do this by simply bumping the versions in packages.json and running npm install.
  2. Create an NgModule: Create a root NgModule in app.module.ts that we use to bootstrap our application.
  3. Update your bootstrap: Updated main.ts to bootstrap our module instead of our root component.
  4. Update your 3rd party libraries: We load up the Forms, Material, Router and Http module in our main app module.
  5. Cleanup: Clean up the code by getting rid of repetitive boiler plate code in our Component annotations.

Revisiting Forms

A couple of months ago I did a rant on forms in angular, and finally they are starting to adress some of the issues. For instance it wasn’t possible to reset a form and its validation in earlier versions, which now is possible. We can simply call a reset method on either a form group or a single control.

Conclusion

Modules is definitely something that we needed to be able to get rid of a lot of boiler plate code in our components. Even if my opinion is that it’s a bit late to introduce this in between two release candidates the end result weighs up for it. I’ll try to do a separate screen on lazy loading modules, which is really easy now.

 

Hope this screencast helped you migrate to RC5 and learn more about modules in Angular.
Until next time, have an excellent day!

Git Deploying a Bundled Angular 2 App using Angular CLI to Microsoft Azure

In this screencast I use the angular-cli tool for the first time to package an angular2 app for production before git deploying it to Microsoft Azure.

Screencast

Angular CLI

The CLI is at the moment of writing in beta and very much still a work in progress. It’s an excellent tool imho for scaffolding a new project, components and services. In this screencast we ran the following commands:

  ng new PROJECT_NAME // creates a new project
  ng g component COMPONENT_NAME // creates a new component
  ng g service SERVICE_NAME // creates a new service
  ng build -prod // builds a production ready version
  ng serve -prod // serves a production ready version

The CLI allows you to do a lot more, I really recommend you to install it and play with it for yourselves.

  npm install -g angular-cli

Also make sure to check out their official github repo which serves as great documentation.

Git Deployment

In this screencast we took a couple of short cuts, we didn’t setup a full CI environment. We initialized a new git repository in the dist folder and pushed only that folder to azure, meaning we built it on our dev machine, big NO NO. The workflow we want would look something like this instead.

  1. We commit a code change.
  2. Agent gets the latest code and builds it.
  3. Tests are run on build agent.
  4. If tests pass, deploy the dist folder to a staging slot.

Nevertheless we still need to enable a git repository for our web app, here’s an excellent guide on how to do that, it basically takes you through the steps I did in the screencast. Basically from the dist folder:

  1. git init
  2. git add *
  3. git commit -m “Initial Commit.”
  4. git remote add azure GIT_CLONE_URL
  5. git push azure master

These commands should fire up an authentication dialog and once you’ve provided the credentials the files should be pushed to the site.

Summary

With these steps we’ve managed to create a production build of an angular 2 app and deployed it to Azure. We did it all with just a few command lines using the angular CLI which was pretty awesome. The CLI does lagg behind the release candidates and is a work in progress so please use with caution.

Until next time, have an excellent day!

Angular 2 Upgrading to new 3.0 Router

In this episode we upgrade the ng2play repo to leverage the new 3.0 router and implement a route guard to protect components that require authentication. Here’s the entire changeset, not that bloody considering the changes but this is also a very small application.

Screencast

Defining Routes

With the old router we decorated our app component with the RouteConfig annotation to configure the routs.

  @Routes([		
    { path: '/', component: Todo },
    { path: '/about/:id', component: About },
    { path: '/profile', component: Profile}		
  ])
  export class AppComponent { ... }

With the new router the routing configuration is no longer bound to a specific component, instead we make it accessible as a provider by exporting it as a const from a separate routes.ts file. Another essential change is that we need to remove the forward slash in the beginning when defining the path.

  import { provideRouter, RouterConfig } from '@angular/router';

  export const appRoutes: RouterConfig = [
    { path: '', component: Todo },
    { path: 'about/:id', component: About },
    { path: 'profile', component: Profile }
  ];

  export const APP_ROUTER_PROVIDER = provideRouter(appRoutes);

Wich we can pass in to the bootstrap function in boot.ts instead of passing ROUTER_PROVIDERS as we did earlier.

import {APP_ROUTER_PROVIDER} from './routes';

bootstrap(AppComponent, [
  ...
  APP_ROUTER_PROVIDER,
  ...
]);

Route Parameters

A component that we route to can access information about route parameters, query parameters and URL fragments by something called, ActivatedRoute, which we can inject into the constructor. The key difference is that route parameters can be accessed through the params property as an Observable or by the snapshot property if subscribing for future changes is overkill. Here’s both ways in our about.ts component:

  import {Component, OnInit} from '@angular/core';
  import { ActivatedRoute } from '@angular/router';

  @Component({
    selector: 'about',
    template: `Welcome to the about page! This is the ID: {{id}}`
  })
  export class About implements OnInit {
    id: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
      this.id = this.route.snapshot.params['id'];
      this.route.params
        .map(params => params['id'])
          .subscribe(id => {
            this.id = id;
        });
    }
  }

Guarding routes

Previously we could prevent our components from activating for unauthenticated users by using the @CanActivate and @CanDeactivate annotations. The guarding logic could be put inside a callback function:

import {CanActivate} from '@angular/router';
@Component({ ... })
@CanActivate(() => tokenNotExpired())
export class Profile { ... }

This approach suffered from that we don’t have access to the applications dependency injection and that we need to decorate each component class with it. The new router solves these problems, we can easily create an auth-guard injectable service that we can pass in to the route configuration accordingly:

  import { provideRouter, RouterConfig } from '@angular/router';
  import { AuthGuard} from './auth-guard';

  export const appRoutes: RouterConfig = [
    { path: '', component: Todo },
    { path: 'about/:id', component: About },
    { path: 'profile', component: Profile, canActivate: [AuthGuard] }
  ];

  export const APP_ROUTER_PROVIDER = provideRouter(appRoutes);

The auth guard has access to the applications dependency injection and we can redirect the user to the root component if they are not allowed to navigate to the component.

import {tokenNotExpired} from 'angular2-jwt';
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (tokenNotExpired()) {
      return true;
    }

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

Let’s also not forget that we’ll need to pass the auth-guard to our bootstrap method to be able to resolve the dependency:

import {APP_ROUTER_PROVIDER} from './routes';
import {AuthGuard} from './auth-guard';

bootstrap(AppComponent, [
  ...
  APP_ROUTER_PROVIDER,
  AuthGuard
  ...
]);

Summary

With these steps we’ve managed to migrate our application to the new 3.0 router, quite frictionless seemingly, but imho they started calling angular2 for RC way too early. It’s still moving too much to even consider using this for production anytime soon.

Until next time, have an excellent day!

Getting Started with Angular2 RC1 and AspNet Core 1.0 RC2 using VisualStudio 2015 and Gulp

In this weeks screencast we start on a new page, to create a new angular2 and aspnet core seed project using the latest release candidate versions. My earlier series contains many upgrade from beta x to beta y episodes, even alphas, it’s starting to become messy to follow, hence the file new project. Make sure to star the project on github, available at https://github.com/ajtowf/aspnetcore-angular2-seed.

Screencast

Until next time, have an excellent day!

Angular 2 Material First Look

In this weeks screencast we take a first look at the material components for angular2 that just released their first alpaha, code at https://github.com/ajtowf/ng2_play. We’ll integrate the button and checkbox component into our ng2play repo, the idea is to fully replace bootstrap down the road.

Screencast

Components

There will be breaking changes between alpha releases, first release of angular2-material includes the following components:

To learn more about material deisgn and components for angular, make sure to check out my pluralsight course Angular Material Fundamentals.

Until next time, have a nice day folks!

Angular Material Fundamentals Course at Pluralsight

Angular Material Fundamentals course released at pluralsight, make sure to check it out here, https://www.pluralsight.com/courses/angular-material-fundamentals, course trailer below:

Hope you guys enjoy the course and learn a lot, and as always, have a nice day!

Build automation for Angular 2 and TypeScript with Gulp

In this screencast we focus on creating a smooth workflow, we’ll build, run code analysis and serve the code, all with gulp. We also learn how to keep the browser in sync with the code. Let me know what you guys think.


Source code @ https://github.com/ajtowf/ng2_play/

Setup npm and gulp

Start off by installing gulp globally and then run npm init to create a packages.json file. Then install the gulp modules we’ll use locally.

npm install -g gulp
npm init // answer the questions, default values are OK
npm install gulp gulp-typescript gulp-sourcemaps gulp-tslint --save-dev
npm install browser-sync superstatic --save-dev // for serving the app

Create the following files in the root directory: gulpfile.js, gulp.config.js and tslint.json

Serve the application

Now that we have everything setup, we’ll get our code analyzed, compiled, served and updated as we save changes to our files just by typing:

gulp

Pretty neat, right? I hope you guys enjoyed the screencast, until next time, have an excellent day!

Aurelia Validation

In this screencast we implement validation in our simple todo application that we created here, it’s basically the same exercise as we did in the angular 2 forms screencast, make sure to check it out if you missed it. The idea is to compare aurelia with angular2, imho aurelia is winning the race right now, let me know what you think.

Steps to get validation with Aurelia

If you’re new to aurelia, make sure you check out my first screencast on aurelia here, before you follow these steps on how to implement validation.

Install the validation plugin by executing the following command via JSPM:

jspm install aurelia-validation

 
And change the aurelia-app attribute to aurelia-app=”main”.

<body aurelia-app="main">

 
The aurelia framework will now bootstrap the application by looking for your main.js file and executing the exported configure method. Add a new main.js file with the following contents:

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-validation'); 

  aurelia.start().then(a => a.setRoot('app', document.body)); 
}

 
Once you’ve loaded the plugin, validation is set up using the fluent validation API in the view model (borrowed from http://aurelia.io/validation/#/).

import {Validation} from 'aurelia-validation';
export class Person {
  static inject() { return [Validation];}
  constructor(validation) {
    this.firstName = 'John';
    this.validation = validation.on(this)
      .ensure('firstName')
        .isNotEmpty()
        .hasLengthBetween(3,10);
  }
}

 
With the following template:

<template>
  <form role="form" validate.bind="validation">
    <div class="form-group">
      <label>First Name</label>
      <input type="text" value.bind="firstName" class="form-control" >
    </div>
  </form>
</template>

 

That’s it, you’re done! You don’t need to mess around with annotations and keep track of what needs to be passed as viewBindings or directives to the template as seen in angular 2 forms. Honestly, it just works!

Conclusion

For the moment Aurelia feels a lot more finished and easier to use. I was struggling with getting angular2 forms up and running and it’s poorly documented, whereas I could just follow the documentation on the aurelia validation github repo and be up and running within minutes. Let me know what you think in the comments, it’s OK to disagree! ;-)

Anyways, I hope you guys enjoyed the screencast, until next time, have an excellent day!
 

Source code as always at @ https://github.com/ajtowf/ng2_overview/

Pluralsight Author

My last couple of screencasts, including the last blog entry was about angularjs 2.0 and aurelia. That’s because I decided to audition for producing courses for pluralsight, and guess what — I’m now an approved pluralsight author. If you don’t know what pluralsight is, here’s a definition by google (authored by themselves?):

Pluralsight is the leading online provider of tech and creative training for professionals.

The audition

To become an author for pluralsight, you need to do an audition. There’s a hard time limit on 10 minutes and you should cover a topic completely in this time, having an introduction, main part and a summary. You can obviously do some assumptions about the viewers’ prior knowledge since 10 minutes really isn’t that much of time. I did a module on bootstrapping the application with angularjs 2.0, as if it was a part of a larger course. You can see it here below, let me know what you guys think!

Time spent

I spent a day familiarizing myself with the framework and producing an example, you’d save some time if you pick a topic you already know of course. Then another day editing and revising the video, bear in mind I hadn’t used the video editing software, camtasia, before. All and all, including emailing back and forth with my acquisition editor I spent roughly two work days, 8 hours each. Was it worth it? Well, we’ll just have to wait and see, so far it hasn’t been too much work in my opinion.

I really look forward to producing a course in the next couple of months. Until next time, have a nice day!