Master the fundamentals of React and Redux

Getting Started Fast with Angular 2 CLI

No more excuses to get started with Angular 2. Discover how the Angular CLI can ease your life when working with Angular 2.

Previously on Setting Up an Angular 2 Environment Using Typescript, Npm and Webpack I explained how to set up an environment to getting started with Angular 2 and TypeScript. If you haven’t read it, please go on! As you may have noticed, the setup is a big part when getting started with Angular 2. You have a lot of things to do before being able to run your app:

The main goal is to get started fast with just one command line. Indeed, this tool allows to build an Angular 2 application, test it, deploy it in production and reiterate. It is just not for demos or prototypes, it will also support large applications as well. All the setup steps shown above are now condensed into some quick command lines.

Let’s install the CLI and explore its features.

Installing the Angular 2 CLI

First step: we have to install the Angular 2 CLI using npm (by the way, we need Node 4 or greater).

1

2

3

npm install angular-cli-g

Install it globally with npm so that the CLI is available wherever you need it.

Now we can play with the CLI to build our application.

Starting a New Application

The next step is to start-up a new project. As I said before, all we need is just… one command line:

1

2

3

ng neweloquentwebapp

So what happened? We have a new directory structure that has been created. Let’s take a look at it.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

eloquentwebapp/

// configuration files

├──config/

│├──environment.dev.ts

│├──environment.js

│├──environment.prod.ts

│├──karma-test-shim.js

│├──karma.conf.js

│└──protractor.conf.js

│

// the build folder. Not created yet...

├──dist/

│

// end-to-end-tests

├──e2e/

│├──app.e2e.ts

│├──app.po.ts

│├──tsconfig.json

│└──typings.d.ts

│

// npm dependencies

├──node_modules/

│

// public assets, global css files, ...

├──public/

│

// where all the application lives

├──src/

│├──app

││// the first component files

││├──eloquentwebapp.component.css|html|spec.ts|ts

││├──environment.ts

││├──index.ts

││└──shared

││└──index.ts

│├──favicon.ico

│├──index.html

│├──main.ts

│├──system-config.ts

│├──tsconfig.json

│└──typings.d.ts

│

// typings and overall configuration

├──typings/

├──.clang-format

├──.editorconfig

├──.gitignore

├──angular-cli-build.js

├──angular-cli.json

├──package.json

├──tslint.json

└──typings.json

Pretty cool, right?! We have a nice application structure that will serve as the foundation of our Angular 2 applications. Furthermore, note that this generated directory structure follows the recommendations in the style guide. I highly recommend to have a look at it.

That’s not all: the Angular CLI will not only create the application structure, it will also initialized git and install any packages required via npm. Check out the default package.json that has been created.

All the dependencies needed to run the Angular application has been added, System.js has been configured, and the app has been bootstrapped. That’s awesome ! All the work we used to do before to get started is now taken care of for us with just one simple command line.

ng new options

--dry-run: only output the files created and operations performed, do not actually create the project. Alias: ‘d’.

--verbose: output more information. Alias: ‘v’.

--skip-npm: do not run any npm command once the project is created.

--skip-git: do not create a git repository for the project.

--directory: parent directory to create the new project into.

Testing our Application

The Angular CLI has generated the unit tests along with our component. See src/app/eloquentwebapp.component.spec.ts:

We are also able to run those unit tests using Karma with the following command:

1

2

3

ng test--no-watch

By default, the CLI keeps running the tests. Use the --no-watch flag to stop testing once all tests have run.

Note that tests are executed after a build is successfully executed. As mentioned in the log, the build artifacts is stored in the dist/ directory. You can also create a build of your project independently from the ng test command line by running:

Serving our Application

Once again, with a single command line we can now run our application in the browser.

1

2

3

ng serve

In my previous post, I explained how to create a server using lite-server and even how to configure Webpack for running the development server webpack-dev-server. Although it was a pretty straightforward task, the Angular CLI is now building a server and serving our application for us.

ng serve options

--port: HTTP port used by the server. Default is 4200.

--live-reload-port: HTTP port used by LiveReload server. Default is 49152.

Running End-to-End Tests

If your were wondering about end-to-end testing, the Angular CLI can also handle it for you. You can run all your end-to-end tests via Protactor by running the following command:

1

2

3

ng e2e

Make sure the server is running via ng serve before running your tests.

You can find those generated tests at e2e/app.e2e.ts:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

import{EloquentwebappPage}from'./app.po';

describe('eloquentwebapp App',function(){

let page:EloquentwebappPage;

beforeEach(()=>{

page=newEloquentwebappPage();

});

it('should display message saying app works',()=>{

page.navigateTo();

expect(page.getParagraphText()).toEqual('eloquentwebapp works!');

});

});

Using the CLI to Scaffold out our App

Another interesting feature of the Angular CLI is the ability to generate scaffolds only by running a command line. For instance, here’s how to generate a new component:

1

2

3

ng generate component foo

Hence, the following files structure is created for us within the src/app folder:

1

2

3

4

5

6

7

8

9

10

src/

└──app/

└──foo/

├──foo.component.css

├──foo.component.html

├──foo.component.spec.ts

├──foo.component.ts

└──index.ts

Note that our generated component lives by default in its own directory. Moreover, it contains all the files needed to get started fast with a new component: class, test, style sheet, and markup.

The CLI can do even more for us. We can also generate a new directive, pipe, service, or route:

ng generate directive <path/to/directive-name>

ng generate pipe <path/to/pipe-name>

ng generate service <path/to/service-name>

ng generate route <path/to/route-component>

Here are the options that we can use along with the ng generate command:

ng generate options

--flat: Do not create the code in its own directory.

--route: Specify the parent route. Only for generating components and routes. Default to the path specified.

--skip-router-generation: Skip generating the route config for the parent. Only usable for routes.

--default: Specify that the route should be a default route.

--lazy: Specify that the route is lazy. Default to true

--inline-template: The template markup is stored directly in the @Component decorator, and not in a separate file.

--inline-style: The style is stored directly in the @Component decorator, and not in a separate file.

Now let’s see in details what gets created when generating a new route and how the Angular CLI makes our life easier.

Generating a Route

As I said before, you can generate a new route with:

1

2

3

ng generate route dashboard

Generating a route with the CLI creates a directory which contain our new component and its related test and style files as before. The generated route will also be registered within our top level component. Let’s have a look at eloquentwebapp.component.ts:

Note that the ROUTER_DIRECTIVES and the ROUTER_PROVIDERS have been imported and injected into our top-level component. Plus, the generated route /dashboard was registered with the component’s @Routes decorator.

You may have also noticed the + prefixing the name of the folder. This + referred to a lazy route which means that it will be loaded on demand. In others words, the route is loaded when needed, and not upfront when the application starts. Read more about this convention in the official style guide.

Once again, the CLI does a great job to ease our development. This time, we don’t have to worry about routing and loading components. The Angular CLI handles it for us.

Deploying our Application

Finally, once your app is ready you can deploy it quickly via GitHub Pages:

1

2

3

ng github-pages:deploy

After building the application for production and setting up the GitHub repository, the app is then published. Refer to the official repository if you need more details about the steps performed during deployment. Find below the options you can pass along with this command:

ng github-pages:deploy options

--message: Commit message to include with the build. Defaults to “new gh-pages version”.

--environment: The Angular environment to build. Defaults to “production”.

--branch: The git branch to push the pages to. Defaults to “gh-branch”.

--skip-build: Skip building the project before publishing.

--gh-token: API token to use to deploy. Required.

--gh-username: The Github username to use. Required.

More Features

In addition to the commands we have already seen, the Angular CLI in v1.0.0-beta.5 comes with others useful commands such as:

ng init: Creates a new Angular project in the current folder.

ng doc: Opens a browser window with the keyword as search in Angular documentation.

ng format: Formats the code of this project using clang-format.

ng get: Get a value from the Angular CLI configuration.

ng set: Set a value in the Angular CLI configuration.

ng lint: Run the codelyzer linter on your project.

ng version: Outputs the version of angular-cli, node and the operating system.

Conclusion

The Angular CLI is an amazing tool to set up your environment quickly for Angular 2. All the work is done for you by the CLI, so you have no more excuses to get started with Angular 2. At the time of this writing, the CLI is in v1.0.0-beta.5 and amazing features are still to come such as:

Can you tell me which command line you are trying to run? If it is a problem with the angular-cli, don’t hesitate to report an issue on the official Github repository: https://github.com/angular/angular-cli

You need to add the directory that contains the angular-cli package in your PATH. It should be something like : C:UsersAdministratorAppDataRoamingnpmnode_modulesangular-clibin

After that, open a new command prompt and run ng again.

WELCOME

About Eloquent WebApp

EloquentWebApp is a resource for Software engineers, Web Developers and JavaScript professionals that want to invest in their skills. Time is precious, choose a lesson and start learning something right now.