Beginners guide to Angular CLI

Hello Everyone in this blog we will learn how to utilize the functionalities provided by Angular CLI to create a new Angular 5 App. And we will see different commands available in Angular CLI to increase our productivity.

CLI (Command Line Interface):

Before we discuss about Angular CLI, let’s have a small discussion on CLI, CLI stands for Command Line Interface, and many other programming languages already have CLI available for different purpose.

For eg. Maven has command line tool to install packages and run different commands, npm already has different command line tools available and same goes to python.

If you notice one thing is common in above example, all technologies are open source, and they are available on any platform. and same goes to Angular, Angular is also platform independent, we can do angular development on any OS and deploy on any server.

CLIs gives you commands which we can execute from our machine and working directory to speed up our development, as we don’t have to rely on any specific IDE. And nowadays everyone has there on CLI available, if we talk about cloud development Azure, Google Cloud and AWS has there own CLI available as well.

Why Angular CLI was Needed:

Now as we have idea about what we mean by CLI, now let’s discuss why actually there was need to have angular CLI.

As we are aware that Angular is open source and we can choose any OS, also we have option to choose from any IDEs, the one which i prefer is Visual Studio Code as it has good support for Typescript.

The problem here is creating skeleton of our project, as we had to do it manually from AngualrJs days, the creation of skeleton includes, creating folder structure, setup the configuration for Karma and Protractor for executing Unit Test cases and End to End cases respectively, installing all the packages via npm, writing gulp or grunt task to minify the application on production, and make sure we are not missing on something.

When Angular 2 was launched the setup was different from AngualrJs,and people used to invest more than 2 days to create skeleton of initial project. This is where Angular team decided to launch CLI,so we don’t have to struggle with all this, and as a developer we should concentrate on doing development.

INSTALLATION:

Before we can go ahead and install angular CLI, we need to install node and npm.

We can download and install Node from here.

Once node is installed please run below commands from command prompt to verify if node and npm is installed properly.

  1. node -v : This command will give is the installed version of node
  2. npm -v:This command will give us the installed version  of npm

Once node is installed, we can run below given command from command prompt

  1. npm install @angular/cli -g : here with -g we are specifying that the package needs to be installed globally, so we can run cli commands from any location on our machine.
  2. ng –version: To verify which version of cli we have installed.

Before installing make sure we are not behind any proxy, as while running npm commands from your organisation you may get error, so before running npm commands, please check if we have access to http://registry.npmjs.org/ if not check within your organisation for how to configure NPM.

In most of the cases its simply setting the proxy using below command:

npm config set proxy http://<username>:<password>@<proxy-server-url>:<port>

Commands:

Now as we have installed node and Angular CLI, let’s go ahead and see how to use different commands from Angular CLI.

Creating New App:

To create a new app we can simply fire “ng new <dir_name>” once this command is executed from command prompt CLI will create the entire app with default template in the directory name provided, it will also create the directory. The template contains the Karma and Protractor configuration as well, and uses the css by default for styling.

But what in case we don’t want these configurations and want to use SCSS file, don’t worry we have other options as well while creating a new app.

  • ng new <dir_name> –style <css/scss> : By default its css but in case we want to use scss we can specify it using –style parameter.
  • ng new <dir_name> –minimal: This will create an app with minimal configuration, does not include Karma and Protractor configuration also css and html will be part of component file only.
  • ng new <dir_name> –skip-tests: This command will skip creation of unit test case file. 
  • ng new <dir_name> –skip-install: This command creates the project skeleton, but will not download the dependent packages.
  • ng new <dir_name> –inline-style: With default configuration we get separate css files for each component, but this option will include the css as part of component.ts files as inline styles.
  • ng new <dir_name> –inline-template: Similar to css we get separate file for our views, this option will use html as a part of component, where we have to provide entire html in template property.
  • ng new <dir_name> –dry-run: This command is only to check which files will be create when we run the command without using –dry-run parameter.
  • ng new <dir_name> –service-worker: Service worker is a new feature introduced in Angular 5, the minimum requirement to use this feature is Angular 5 and CLI 1.6, this feature enables us to run our app in offline mode.This command will help us to have default configuration available to use this functionality

Below is the example of Folder structure and output of ng new command.

 

Creating Different Files:

Apart from creating new app, CLI also helps us to create different files to be used in Angular App, so we don’t need to create them manually. Let’s see the commands next.

We can use “ng generate” or “ng g” command to add different files.

Common Commands:

There are few command which can be used with all types of files, let’s see them first.

<file_type> : c/module/service/guard/directive/pipe  — Available options for file type

  1. ng g <file_type> <name> –dry-run/-d/-dryRun : This commad will show the changes which will be made, without making actual changes.
  2. ng g  <file_type> <name> –force/-f/-force : Force overwriting of files in case they exist.
  3. ng g  <file_type> <name> –flat : CLI creates a folder for every component/module and skips the folder creation for directive/service/guard,if this is specified creation of folder will be skipped and all files will be created in app folder, if we provide this as false a folder will be created.
  4. ng g <file_type> <name> –spec true/false : if provided as false, CLI will skip creating the .spec.ts.
  5. ng g <file_type> <name> –lint-fix/-lf/-lintFix: This command will fix linting error,if any after file generation.
  6. ng g <file_type> <name> –module/-m <value>: We can also specify the module name in which the file needs to be registered.

NOTE: We can specify multiple options in a single command to utilize the multiple options together.

Component: 

To add a new component in our app, we can use “ng g c <component_name>” this command will create a component in our application created using angular CLI. For example if we want to create EmployeeComponent in command just pass “ng g c Employee” CLI creates 4 files by default for component. Below is the files which will be created.

  • employee.component.css : This is a css file where we can write our css code.
  • employee.component.html : This is where we will write the html to be rendered
  • employee.component.spec.ts : This file is for writing our unit  test cases.
  • employee.component.ts : This is where we will be writing our Typescript code for component. 
  • Let’s see some other optins which we can use with “ng g c <component_name>” command.
    1. ng g c <component_name> –inline-styles : In this case .css file will not be created, the css will be part of .component.ts  files.
    2. ng g c <component_name> –inline-template : If sepecified the .html file will not be created, it will part of .component.ts file.
    3. ng g c <component_name> –view-encapsulation none/emulated/native : We can define the encapsulation strategy, we can choose from none/emulated/native.
    4. ng g c <component_name> –change-detection default/onpush : We can define the change detection startegy to be used. if we don’t define any value default is used, or define onpush.
    5. ng g c <component_name> –skip-import : By default CLI add the component created to modules declarations array, if specified CLI will skip the entry.
    6.  ng g c <component_name> –selector <value>: In case we don’t want CLI to create selector name, we can specify one.
    7. ng g c <component_name> –export : If specified the CLI will also add the component to exports arrays of angular module. 
    8. ng g c <component_name> –prefix/-p <name>: By default CLI use “app” as prefix for all components, in case yo want to override there are 2 ways, change this in .angular-cli.json file or it can be provided in command.
    9. ng g c <component_name> –styleext <value> : We can specify which style-sheet format to be used by default css will be used, but we can specify scss as well. In case while creating the app, if we have used scss, than scss will be created by default.

Angular Module:

When we create an app using CLI, by default CLI creates an Angular Module for us, which we can find in app folder and it is named as app.module.ts , the reason being Angular app requires at lease one Angular Module to be there, which will be used as root module. But in case we want to create more angualr modules we can go ahead and do that, the command used to create and angular module is “ng g module <module_name>”

Let’s see multiple options which are available for this command:

  1. ng g module <module_name> –routing: In case we need a seperate file where we want to define all our routes for a particula module, we can use this option. It will create 2 files, one for module and one for routing configuration. Let’s say we fire ng g module order –routing the output will be 2 files shown below 
  2. ng g module <module_name> –common-module true/false: When we create a new Angualr module using CLI, by default an module names CommonModule is imported, but in case for a specific module, we don’t want this is to be imported by default we can pass this option

Services:

Like all other programmig langauage services are most important in Angualr apps as well, we widely use services to write some common logic(reusable codes), share data between multiple components, also to interact witg our rest apis. we can use “ng g service <service_name>” command to create a service.

CLI does not registers and creates an folder for services by default. Make sure in case you want services to be created inside a folder, fire this command from that folder, for ex: in case i want services to be created inside Order folder, we need to create and Order folder and than ove to that folder from command prompt.

CLI creates 2 files by default, let’s say we fire “ng g service employee” we will get below shown files.

Directives:

Directives are really important when we want to do some DOM manpulation in Angular, they are almsot similar to components but they don’t have there own views.

We can use “ng g directive <directive_name>” directives don’t have .css an .html files.

For eg: if we execute “ng g diretive hover” 2 files will be created named “hover.directive.ts” and “hover.directive.spec.ts”.

Let’s see other options apart from common commands below:

  1. ng g directive <directive_name> –selector <value>: In case we don’t want CLI to create selector name, we can specify one.
  2. ng g directive <directive_name> –export : If specified the CLI will also add the directive to exports arrays of angular module. 
  3. ng g directive <directive_name> –skip-import : By default CLI add the directives created to modules declarations array, if specified CLI will skip the entry.

Pipes:

Pipes are used in angualr to transform the data when it is being rendered in UI. we can use “ng g pipe <pipe_name>”. CLI cretaes 2 files for pipes, also registers the pipe with root component.

Let’s see other options apart from common commands.

  1. ng g directive <directive_name> –export : If specified the CLI will also add the pipe to exports arrays of angular module. 
  2. ng g directive <directive_name> –skip-import : By default CLI add the pipes created to modules declarations array, if specified CLI will skip the entry.

Guard: 

Guards are one of the most important feature introduced in routing with Angular 4. We can use “ng g guard <guard_name>” to create a new guard.

The guards are similar to services they needs to be registered as well to be used.

Running Application:

To check if our application is working fine, we need to run it locally to see how it works and behave. we can use “ng serve/server/s” 

Once you get message like above on command prompt, open chrome and enter http://localhost:4200/.

We should get below UI. This is kind of getting started page for Angular.

Let’s see some other options which are available with this command.

  1. ng serve –target/-t/-dev/prod <envorionment> : We can define the build target. By default it uses development, we can use production as other options, we can define more options for environment. In case we are using -dev or -prod options environment is not required as -dev stands for –target=development and   -prod is for –target=production.
  2. ng serve –environment/-e <value> : Define the build environment.
  3. ng serve –sourcemaps/–sm/–sourcemap <true/false> : We can define if source maps should be created or not, if we disable it, we won’t be able to debug our app.
  4. ng serve –open <true/false> : If this option is specified, the application will be loaded in default browser once build is successful.
  5. ng serve –ssl <true/false> : If specified application will run in https mode.
  6. ng serve –ssl-key/–sslKey <kep_path> : We can specify the ssl-key file to be used,when running in https mode.
  7. ng serve –ssl-cert/–sslCert <cert_path> : We can specify the certificate path to be used in https mode.
  8. ng serve –live-reload/-lr/–liveReload <true/false> : By default angular app reloads in case any changes are made in app, we can control if we want to do that.
  9. ng serve –port <port_number> : By default angular CLI uses 4200 port to run the app, but we can specify the port here, in case 4200 is already in use.
  10. ng serve –watch <true/false> : By default angular apps run in watch mode, we can control the same using this flag.
  11. ng serve –poll <time> : Enable and define the file watching poll time period, time is in millisecond.

Running Test Cases:

There are 2 types of test cases which can be written in Angular, Unit Test and Automatin Test case. CLI by default provides the configuration for both.

Unit Test Case:

The files created inside our app directory and ending with .spec.ts are considered as Unit Test case files. The code is written using Jasmine and can be executed using “ng test” command.

Let’s see other options available:

  1. ng test –progress : This command will log the progress of application build to console, this is enabled by default.
  2. ng test –code-coverage : If specified we will get the code coverage report in coverage folder, the coverage report looks like below.
  3. ng test –config <file_name> : Specify the config file to be used if other than the default config file provided by CLI.
  4. ng test –single-run/-sr/–singleRun : Run unit tests single time.
  5. ng test –browsers <browser_name> : Specify the browser in which test cases will be executed, by default CLI uses chrome.
  6. ng test –port <port_number> :  Specify the port number to be used.
  7. ng test  –reporters <value>: Specify list of reporters to be used.

Automation Test Cases:

In our folder structure there is a folder named e2e, this folder is for Automation or End2End Testing. In Angular we use Protractor for writing End 2 End test cases. To run e2e we can simply use “ng e2e”

let’s see other commands to be used:

  1. ng e2e –config <file> : By default angular CLI gives us as a protractor configuration, but in case we want another config file to be used, it can be specified here.
  2. ng e2e –specs <file> : By default protractor considers all spec.ts files as test cases, but in case we want to execute only 2 or 3 files, this command is useful, we can specify files  like ng e2e –specs=app.e2e-spec.ts –specs=login.e2e-spec.ts
  3. ng e2e –suite <name>: Suites are best way to organize related test cases, in case we want only specific test suites to be executed, it can be done using this option like ng e2e –suite=smoke,regression.
  4. ng e2e –webdriver-update/wu/webdriverUpdate <true/false> : When we try to run test cases, the command will try to update webdriver by default, can be disabled from here.

Creating Deployment Build: 

Once our application is ready for use, the most important thing is to create a deployment build. Its very easy to create a deployment build, in case we are using Angular CLI, we can use “ng build” command to create a dist folder.

Let’s see different commands used for crating deployment build.

  1. ng build –stats-json/statsJson <true/false>: This command create an extra file named stats.json which can be used by webpack bundle analyser which is available here.
  2. ng build –skip-app-shell/skipAppShell <true/false> : App shell comes from angular universal, it will help us to decrease the initial load time of our app. Refer this blog for more details in this feature.
  3. ng build –service-worker/sw/serviceWorker <true/false> : This command will give us the service worker config file to be used in production.
  4. ng build –target/-t/-dev/prod <envorionment> : We can define the build target. By default it uses development, we can use production as other options, we can define more options for environment. In case we are using -dev or -prod options environment is not required as -dev stands for –target=development and   -prod is for –target=production.
  5. ng build–environment/-e <value> : Define the build environment.
  6. ng build –output-path/-op/outputPath <value> : By default CLI creates the output into dist  folder, but i case we want the output into another folder we can specify the folder name here, eg: ng build -op=dev
  7. ng build –aot: If we specify this flag, output will be created using Ahead of TIme Compilation.
  8. ng build –sourcemaps/sm/sourcemap <true/false> : We can define if source maps should be created or not, if we disable it, we won’t be able to debug our app. This is disabled by default in prod mode.
  9. ng build –base-href/-bh/baseHref <value> : On production we generally deploy our code under some context, we need to give the same context name here.
  10. ng build  –output-hashing/-oh/outputHashing=none|all|media|bundles : By default when we create a build, CLI appends some hash to file names to all output files, for cache-busting so whenever a new build is deployed we don’t get into cache issues. we can define the strategy here, in case we want to override for few file types.
  11. ng build –show-circular-dependencies <true/false> : This  command gives us the circular dependency if any in our code, this is enabled by default.
  12. ng build –build-optimizer <true/false>:  This options enables the code optimization provided by  @angular-devkit/build-optimizer, this option is enabled in aot and Angular 5.

CONCLUSION:

Angular CLI is really an awesome tool, to speed up your productivity, also by using it we are making sure that our application is structured and it is really easy to understand the application structure and reduces the effort when app goes in support.

You can reach out to me on santosh.yadav198613@gmail.com for any queries. In our next blog we will discuss about Binding in Angular.

Leave a Reply

Your email address will not be published. Required fields are marked *