Now that Angular CLI is installed and ready to go, we can use it to automatically generate new projects. This lesson will walk through how to create a new project using Angular CLI, including what files it will generate automatically, and how our projects will differ from those we created last week.

Additionally, we'll create an online store application together throughout the curriculum this week. This lesson will begin the application we'll develop for the next few days. However, the setup instructions will be general enough to re-use for any future application you may create. Let's get started!

Creating a New Angular Application

Navigate to the directory you'd like your new Angular application to reside in and run the following command. We'll go ahead and call our project online-store because we'll begin creating an e-commerce website in subsequent lessons.

$ ng new online-store

ng stands for Angular. With this command, we are instructing Angular to create the following necessary files for the project:

installing ng2
  create .editorconfig
  create README.md
  create src/app/app.component.css
  create src/app/app.component.html
  create src/app/app.component.spec.ts
  create src/app/app.component.ts
  create src/app/app.module.ts
  create src/assets/.gitkeep
  create src/environments/environment.prod.ts
  create src/environments/environment.ts
  create src/favicon.ico
  create src/index.html
  create src/main.ts
  create src/polyfills.ts
  create src/styles.css
  create src/test.ts
  create src/tsconfig.json
  create angular-cli.json
  create e2e/app.e2e-spec.ts
  create e2e/app.po.ts
  create e2e/tsconfig.json
  create .gitignore
  create karma.conf.js
  create package.json
  create protractor.conf.js
  create tslint.json
Successfully initialized git.
Installing packages for tooling via npm.

Note that this includes the root directory itself! Also, it may take several minutes for this process to complete. Once the process is finished, you should see this message in the console: "Project 'online-store' successfully created."

Project Directory

Let's take a look at our file directory in Atom (or your preferred code editor):

new-angular-cli-project-directory-in-atom

Let's walk through the files and directories Angular CLI has generated for us.

e2e

This is a directory for tests. e2e stands for "end-to-end". End-to-end testing is similar to integration testing. It explores the application as users experience it and simulates user behavior to confirm the application functions as expected.

This directory will contain app.po.ts and app.e2e-spec.ts files with starter tests and a tsconfig.json file with configurations.

Unfortunately, our two short weeks with Angular don't allow enough time to explore testing. If you'd like to explore Angular testing further, check out the Testing section of the Angular 2 documentation.

node_modules

Angular CLI has already created a node_modules directory for us. If we open the directory, we'll see that many packages are already installed. We can check our package.json file in the top-level of our directory to see included packages:

package.json
  "name": "online-store",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\" --project src/tsconfig.json --type-check && tslint \"e2e/**/*.ts\" --project e2e/tsconfig.json --type-check",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.25.5",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.3.0",
    "typescript": "~2.0.3"
  }
}

Similar to last week, we include many parts of the Angular core framework as dependencies. All packages named karma, jasmine, protractor, or codelyzer are testing-related.

src

src stands for "source." This is the directory that will contain our source code. We'll do most of our development in these files.

The contents of this folder should look like this:

src
├── app
│   ├── app.component.css
│   ├── app.component.html
│   ├── app.component.spec.ts
│   ├── app.component.ts
│   └── app.module.ts
├── assets
├── environments
│   ├── environment.prod.ts
│   └── environment.ts
├── favicon.ico
├── index.html
├── main.ts
├── polyfills.ts
├── styles.css
├── test.ts
└── tsconfig.json

Many of the filenames should already be familiar from last week. Let's start by walking through the files in the top-level of the src directory:

  • favicon.ico contains the small icon that will appear on the browser tab of the running application. You can replace this with your own icon if you'd like. The code to load the icon is in our index.html file.

  • index.html is the index of our page. Its contents will look like this:

src/index.html
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>OnlineStore</title>
    <base href="/">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
  </head>
  <body>
    <app-root>Loading...</app-root>
  </body>
</html>

Notice our root component is already linked with <app-root></app-root> tags directly within <body>.

The "Loading…" text inside the <app-root> tags will be displayed in the short period of time between loading index.html and then rendering the <app-root> component.

src/main.ts
import './polyfills.ts';

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

This file provides instructions for assembling our application when we launch it. It will load our root module, which will then load our root component.

  • polyfills.ts: Last week, we briefly discussed the polyfill scripts included in our index.html file. Remember, a polyfill is code that implements a feature on web browsers that don't technically support that feature. This code compensates for any issues older browsers may experience while running an Angular application. These are many of the same polyfills we previously linked in our index.html files. Angular CLI imports polyfills in this TypeScript file and then loads the file into main.ts.

  • styles.css is our application-wide stylesheet.

  • test.ts is a configuration file for testing. It's responsible for declaring variables used throughout tests and loading the necessary modules when tests are run.

  • tsconfig.json: This file contains our configuration for the TypeScript compiler. Last week, we created our tsconfig.json file manually, but now Angular-CLI creates the file for us.

tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

We can leave this as is.

src/assets

Within src, we also have an assets directory. Any images and outside scripts can be placed in this file.

src/environments

The src directory also contains a subdirectory called environments. It contains two files: environment.prod.ts and environment.ts

  • Our development environment includes all tools, packages, and configurations necessary for development. This includes any testing suites and test files as well as the packages listed in the devDependencies section of our package.json.

  • Our production environment includes only tools, packages, modules, and code necessary in the final, deployed version of the app. This prevents apps from shipping with unnecessary code.

If you'd like to learn more about environments in Angular CLI, check out this blog post: "Angular 2: Application Settings using the CLI Environment Option".

Top-Level Files

Let's discuss the files in the uppermost level of our project directory before returning to the src/app directory where we'll complete most of our coding.

  • .editorconfig: This file helps developers maintain consistent coding style across text editors. For instance, one developer on a team may use Atom while another may use Sublime. These developers can ensure their code is formatted similarly by adding configurations to the .editorconfig file. We won't make any changes to this file but you can check out the EditorConfig entry in the Atom Documentation for more info .

  • .gitignore: Just like last week, we don't need to commit files downloaded by npm or bower to our Git and GitHub repositories. Angular CLI has already created a .gitignore file in the top level of our project directory. We'll add a few more things to this file in the next lesson.

  • angular-cli.json: This contains Angular CLI configurations for building and serving a project. We'll look at this file a little closer in upcoming lessons.

  • karma.conf.js: This contains configuration settings for a testing library called Karma.

  • package.json: As you know, this contains our npm packages. We took a peek at it just a moment ago.

  • protractor.conf.js: This contains configurations for a testing tool called Protractor.

  • README.md: An automatically-generated README. If we open it, we can see some content is already in place:

README.md
# OnlineStore

This project was generated with [angular-cli](https://github.com/angular/angular-cli) version 1.0.0-beta.25.5.

## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

## Code scaffolding

Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive/pipe/service/class/module`.

## Build

Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.

## Running unit tests

Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).

## Running end-to-end tests

Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
Before running the tests make sure you are serving the app via `ng serve`.

## Deploying to GitHub Pages

Run `ng github-pages:deploy` to deploy to GitHub Pages.

## Further help

To get more help on the `angular-cli` use `ng help` or go check out the [Angular-CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

Even though some setup instructions are already in place, don't forget to add your own author name, description of the project, and any additional setup instructions.

  • tslint.json: This contains configurations for the TypeScript linter. Angular CLI includes a built-in linting tool to help notify us of any errors in our code. We'll explore how to use it in an upcoming lesson.

src/app

Finally, let's visit the src/app directory where our source code is stored. It contains the following:

  • An app.module.ts file for our root module with a decorator and import statements to the most common portions of the Angular framework already in place:
src/app/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';

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

  • An app.component.ts file for our root component with an import statement, @Component decorator, and class declaration already in place:
src/app/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!';
}

External HTML Templates

A few things are different from last week. Instead of a template, we have a templateUrl. As you can see, it points to the following file:

src/app/app.component.html
<h1>
  {{title}}
</h1>

Here we are loading an external HTML template located in app.component.html instead of inserting the HTML directly into the component file. The external template, located in app.component.html, still has access to any properties defined in the component. There's already a {{title}} property being displayed in the template. This corresponds to the title property defined in the component's class declaration:

src/app/app.component.ts
…
export class AppComponent {
  title = 'app works!';
}

Component templates located in a different file work exactly the same as component templates located directly in the component file. The only difference is that the component links its template with a templateUrl property instead of including it directly in the component file with a template property.

External component templates have the same name as their corresponding component Typescript files. The only difference is a .html extension instead of a .ts extension.

For instance, app.component.html is the template for the component located in app.component.ts. If we had a component named super-crazy-party.component.ts, its external template (if it had one) would be located in super-crazy-party.component.html.

Component Stylesheets

Notice also the styleUrls property in the component annotation:

src/app/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!';
}

This property already points to a file Angular CLI has generated for us called app.component.css. It's currently empty but we could place any styles specific to this component here.

Also, notice the styleUrls property is an array. We can include the filepath to multiple .css stylesheets here and their CSS rules will be applied to this component.

Testing Files

Additionally, you'll notice a file in the app directory named app.component.spec.ts. This is where any tests for the root AppComponent would reside. This file includes configurations and a few starter tests for our root component. Students interested in exploring testing should check out the Testing Section of the Angular 2 Guides.

Now that we know how to create a new project with Angular CLI and are familiar with the files and directories it generates for us, we're almost ready to begin developing our project.

In the next lesson, we'll address a few more setup steps we need to complete that Angular CLI doesn't automatically handle for us. Then we'll address how to actively build, serve, and develop an application with Angular CLI.