An introduction to Angular CLI - Part 1 - Getting to know the commands

At ng-conf 2016 the angular team announced a new tool called angular cli that makes creating and scaffolding angular applications simple and painless. By now unless you’ve been living under a rock you should have at least heard about it.

We're going to explore and familiarize ourselves with some of the most common commands like new, generate, serve and build by scaffolding a basic to do list.


Before getting started with angular CLI, let’s make sure we have the right version of node and npm running. We should be running at least node version 4.0 and npm version 3.0. Let’s check by going to the terminal and executing the node -v and npm -v commands.


Next, let’s install angular cli. We can do this through npm. We use the install, or i command for short, along with the global flag to make sure the package is installed globally.

$ npm i -g @angular/cli

Now we have everything installed, we’re ready to start making applications.


To create a new application, we use the ng new command. Let’s do this now. Type ng new todo-list --style=scss. This flag tells the cli that we want to use the sass preprocessor for our styles instead of defaulting to css. The new command recognizes a few different flags, such as the style flag we already saw, as well as routing and a few others. I suggest you check out the documentation for a full list of options that are available.

The output tells us that our project files have been created and npm is installing the packages necessary to make our application work, so whilst that happens let’s have a look at some of the files angular cli gives us out of the box.


By default, angular cli gives us the packages and scaffolds files necessary for us to unit test and end to end our applications. Our end to end tests go in the e2e folder in the root directory, and when we generate components and services, we’re provided with spec files for unit testing.


To configure our application, we can change config params in the angular-cli.json file. Amongst other things, we can change the prefix for our components, add external stylesheets and scripts such as jquery and the bootstrap framework and setup our “build” environments.


The source folder is where we spend most of our development time. Angular cli creates a component called app which acts as the root component for our application. As projects start to get bigger, this is where it begins.

The app component is comprised of 4 parts. We’re given a class file where our component code goes, a spec file to write tests, a view and a stylesheet.

The cli also generates a module file where all the declarations, imports and providers can be added.


Let’s have a look at the generate command. Our to do list is going to be made up of three parts, an item interface, a list service and a component to output the list.

First let’s generate the interface. In the terminal, type ng generate (or g for short) interface item.

$ ng g interface item

We can see the interface in our app folder. By default angular cli generates interfaces, classes and services in this folder. We can also specify a folder in the terminal by prepending it before the name, followed by a slash.


Let’s generate our list service in the same way. We’ll type ng g but use service instead of interface this time, and call it list. The CLI will generate a file called list.service, along with a spec file. One thing to note is that the CLI automatically adds Service to end of the filename as well as the class name, so we don’t have to call it list service.

The CLI reminds us that although the service has been created, it hasn’t been provided, meaning if we want to inject it into other components or services, we’re going to have to go through another step in the app.module file. We’ll get to that in a second.

$ ng g service list

Before we switch back to the IDE, let’s generate our list component in the same way. Type ng g component list.

$ ng g component list

Great, now we have everything we need to make our list app.


Let’s start with our item interface. We’re going to keep it really simple, so our interface will consist of just two properties - a title which will be a string, and a due date which will be a date.

export interface Item {  
  title: string;
  dueDate: Date;
}

Now let’s add some code to our list service. We want to hold a list of items, so let’s start by importing our item interface.

import { Item } from './item';  

Next we can create a member variable called items which will be an array of items.

items: Item[] = [];  

Lastly, let’s add a couple of methods to add and delete items from our list. Here's how our ListService looks.

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

import { Item } from './item';

@Injectable()
export class ListService {  
  items: Item[] = [];

  constructor() { }

  addItem(item: Item) {
    this.items.push(item);
  }

  deleteItem(index: number) {
    this.items.splice(index, 1);
  }

}

If you remember, when we generated our service, angular cli warned us that we need to provide it before it can be used, so let’s do that.

All we need to do is import it into our app module file and add it to the providers array.

import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { FormsModule } from '@angular/forms';  
import { HttpModule } from '@angular/http';

import { ListService } from './list.service'; //<- 1. Import ListService

import { AppComponent } from './app.component';  
import { ListComponent } from './list/list.component';

@NgModule({
  declarations: [
    AppComponent,
    ListComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [ListService], //<- 2. Add ListService to providers array
  bootstrap: [AppComponent]
})
export class AppModule { }

Great, now we’re able to inject our list service into our list component constructor.


Unlike our service and interface, when angular cli generates a component, it creates a new folder inside out app folder. There’s a few files it gives us. First we get a component class file where our logic goes. There’s also a spec file for our unit tests, a stylesheet and a view file.

Let’s start with the component logic. First thing to do is import our list service and item interface. Even though we added the list service to our providers in the app module file, we still have to import it into any file we want to use it.

import { ListService } from '../list.service';  
import { Item } from '../item';  

Now let’s inject it into the constructor. We’re going to make it a public variable so that we can use it directly in our view file.

constructor(public list: ListService) { }  

Let’s write some code to generate a few basic items in our component. We’ll use a for loop to add some items to our list. Here's how our component should look.

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

import { ListService } from '../list.service';  
import { Item } from '../item';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent {

  constructor(public list: ListService) { 
    for (let i = 1; i <= 10; i++) {
      let dueDate = new Date(),
          newItem: Item = {
            title: 'Item ' + i,
            dueDate: dueDate
          };

      dueDate.setDate(dueDate.getDate() + i);

      this.list.addItem(newItem);
    }
  }

}

Now we have everything set up, let’s output our list in our html file.


We’re going to loop through our list items and output them to the screen. One thing I always have trouble remembering is the syntax for angular’s ng for directive. Luckily angular cli has a convenient command to help us search the docs.

$ ng doc ngfor

In our terminal, we can type ng doc followed by the search query, in this case “ngfor”. This will open the search results in our default browser.


Now we’re armed with enough knowledge to output our list. We’ll use an unordered list with an ng for, outputting the title, the due date and a delete button that will call our list service’s deleteItem method.

<ul>  
  <li *ngFor="let item of list.items; let i = index">
    {{item.title}}
    <small>Due {{item.dueDate | date}}</small>
    <button (click)="list.deleteItem(i)">&times;</button>
  </li>
</ul>  

The last thing we need to do is add our component to our app component view file. As I said before, the app component acts as the root component of our application.

<h1>  
  {{title}}
</h1>

<app-list></app-list>

Now we have our application coded, it’s time to test it. We can use the cli’s serve command that will do a few things.

$ ng serve

First, it lints our code to make sure there are no syntax errors. Then it builds and minifies everything. Finally it spins up a server that watches for changes and automatically reloads when a file changes.


We can view our application by navigating to localhost on port 4200.


Finally, let’s have a quick look at the build command. Angular cli let’s us build our code using custom variables depending on the environment we’re building for.

For example, we’re looking at the production environment variables. The cli adds a production settings that set’s some options for minification, but we can add our own here too.


Now in our terminal, we can type ng build with the prod flag. Angular goes through the build and minification process and creates a new directory called “dist” with the output files, ready to deploy to a server. It’s really that simple.

$ ng build --prod
comments powered by Disqus