App development made easy: An introduction to Angular 2

Babette Landmesser

Developers have been waiting for this web framework for a long time: On September 14th the first version of Angular 2 was finally released. A few important changes have been made compared to its predecessor AngularJS. In this post we will talk about some of the steps in the development of Angular 2 apps and list a few coding examples.

angular

The basis

One of the tools we highly recommend is Angular-CLI (careful: Angular-CLI requires at least Node v4 and NPM v3). This console tool makes working with Angular easier since you can automatically create a functioning authority with it and both compile and run it. As soon as Angular-CLI is installed, a new Angular 2 project can be created via ng new my-app-name. You run the Angular app through ng serve In the console history you can see with which local URL the application is available:

** NG Live Development Server is running on http://localhost:4200. **

A second starter pack is angular2-webpack-starterkit – another running Angular entity that is compiled through webpack. You can find the code and installation instructions here

The heart of the app

In a nutshell, you can reduce the changes made in Angular 2 to class-based JavaScript and the use of TypeScript when comparing it to AngularJS. Of course a lot of other adjustments have been made, but we will not get into those here.

With component-based scripts you extend the Angular core until an individual app is developed. That is why the application has to be divided into components.

The heart of any app is the file app.module.ts, which is simply a name recommendation. Here, all features come together in various ways. The files are incorporated through imports.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { UsersComponent } from './users/users.component';

@NgModule({
  declarations: [
    AppComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The import lines indicate, which modules from the Angular code are being used. The BrowserModule starts the app, while the NgModule is the app’s “main” module. The base code provides two other modules here that are used often: Forms (for blank forms) and Http, for HTTP requests to load data. Additionally, the parent component called “AppComponent” will be loaded, which includes all other app components as child components (see declarations).

With @NgModule the app module is created. Here, you will find all dependencies and components included in this module. When loading this module, the AppComponent will be started as mentioned at bootstrap.

The components

A component can include different files and only has to hold the file name.component.ts. At this point it would be advisable to distinguish the various front end parts: JavaScript/TypeScript, HTML and CSS. 

The AppComponent in this example looks like this:

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}

The selector indicates how this module is incorporated. There are several options, for example as an HTML element or an HTML attribute. In addition, the path to the template (HTML) and to the style sheet (CSS) is given to the component. With it, you can differentiate the various logics. Nevertheless, there is an option here as well to create all styles and HTML elements inline:

// users.component.ts

@Component({
    selector: 'users',
    styles: [
        `.superuser { color: red; }
        td, th { border: 1px solid #eee; }
        `
    ],
    template: `<h1>Users</h1>
    <table class="table">
      <thead>
        <tr>
          <th>id</th>
          <th>Username</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let user of usersList | async" [class.superuser]="user.superuser">
          <td>{{user.id}}</td>
          <td (click)="onClick(user.username)">
            {{user.username}} 
          <span *ngIf="user.superuser">(superuser)</span></td>
        </tr>
      </tbody>
    </table>`
})

Depending on the extent of the HTML templates and the styling it is advisable to outsource them. Additionally, you can integrate SCSS or LESS at this point and simply compile them into a CSS file.

Use of Angular CLI

With the help of Angular CLI it is easy to generate such components. The command is simple: ng generate component [path], for example ng generate component users.

In the Angular directory at src/app a folder called “users” is created. Additionally, TypeScript as well as HTML and CSS files are generated for this component.

When doing so, Angular already updates app.module.ts and extends it with the new component UserComponent - i. e. a new dependency. In the TypeScript file of the new component the templates and styles are already linked as well:

// users.component.ts

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

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

  constructor() { }

  ngOnInit() {
  }

}

By using the console tools, the error rate drops drastically when creating components, since not only the name conventions but also the according links are defined as dependencies. However, the routing has to get updated accordingly – as far as it exists.

Conclusion: Angular console support is not to be underestimated. You can save a lot of time when creating apps and components with it. In addition, the learning barrier is reduced, since you don’t have to make your way through a flood of files that might have to get installed for a mere Angular 2 app – the compilation of TypeScript to comprehensive JavaScript for the browser is already included and you can start right away. Wherever Angular 2 may take us – it will certainly be exciting!

If you want to get an idea of what you can produce with Angular 2, you should take a look at Angular Expo.

Our expert

Babette Landmesser

Any questions or input? Reach out to our experts!

Send e-mail

Babette Landmesser works as a Frontend Developer for Cocomore since April 2015. Before, she was a self-employed Frontend and WordPress Developer. Through her work with among others WordPress, Drupal and JavaScript she especially appreciates the versatility at Cocomore.
Babettes motto: „A day without laughter is a day wasted."