What Is Angular CLI?

What Is Angular CLI?

The Angular Team created the command-line interface, or CLI, for Angular. With the aid of this tool, we can immediately begin building the Angular Application. Using the Angular CLI commands, we will develop and manage the Angular app in this article. The commands ng new, ng generate component, ng generate directive, & ng generate pipe will be covered, among others.

Why Angular CLI

Front End Framework Angular is simple to learn. However, creating a development environment is quite difficult. When you select Angular as your JavaScript Framework, you have a lot of options.

Dart, Typescript, and Javascript are your options. SystemJs, Webpack, and other module loaders must be selected. Pick up your testing framework immediately. All of this was covered in our article on setting up an Angular development environment.

Once a decision has been made, numerous libraries and packages have been set up. These libraries each have their own configuration files included. For instance, you must add all necessary libraries to the Package.Json file that you build. Make configuration files for Webpack or SystemJS. For Typescript, configuration files are also necessary.

What is Angular CLI

With just one command, the Angular CLI enables you to quickly create an Angular application with all the necessary configuration files and packages. It also enables us to enhance already-built Angular apps with new functionality (components, directives, services, etc.). It assists us in testing, creating, and distributing our application.

The Angular CLI leverages Typescript, Webpack (for module bundling), Karma (for unit testing), and Protractor (for end-to-end testing) to generate the Angular application.

Installing Angular CLI

Installing the Angular CLI is the first step. The following command can be used to accomplish this.

npm install -g @angular/cli@latest

The aforementioned command updates your computer's Angular CLI to the most recent version. The -g flag, which stands for global and installs the Angular CLI system-wide so that you can use it in all of your projects, is what you should take note of.

Angular CLI Versions

Angular CLI Version Check

Use the Command to Determine the Current Installed Angular CLI Version.

ng --version

13.2.5 is the most recent version as of the writing of this article. The tool mentioned above also outputs the version of the node that is installed on your system.

Angular CLI Commands

CommadAliasDescription
helpHelp message shows the List of available commands and their short descriptions.
versionvFind out the version of the Angular CLI Installed
newnCreates a new folder (Workspace) and ads the initial Angular app. Note that you can create multiple apps in a single folder (Workspace)
addAdds the npm package to the workspace and configure the default app project to use that library.
generategGenerates and/or modifies files based on a schematic.
updateUpdates your application and its dependencies
servesBuilds and serves your app, rebuilding on file changes.
runRuns a custom target defined in your project.
buildbThe Compiles the Angular app into an output directory ( Default is dist)
testtRuns unit tests in a project.
e2eeBuilds and serves an Angular app, then runs end-to-end tests using Protractor.
config Retrieves or sets Angular configuration values.
docdOpens the official Angular documentation (angular.io) in a browser, and searches for a given keyword.
lintlRuns linting tools on Angular app code in a given project folder.
xi18nExtracts i18n messages from source code.


Getting Help

ng help

The syntax ng [command name] --help is used to request help for certain commands. As An Example

ng add --help       //help on add command
ng new --help       //help on new command  

Creating the Application with ng new

The ng new command builds an app using the name specified and creates a new folder.

ng new 

Your response to the order

  • What name do you want to give the endeavor?
    The project's name should be entered here. “GettingStarted”
  • Do you want to include Angular Routing?
    Unless you do not wish to add Angular Routing, select Yes.
  • Which stylesheet format are you interested in using?
    You can use the arrow keys to choose from the various CSS, SCSS, SASS, LESS, and Stylus options.

With the aforementioned command, all necessary dependencies and configuration settings are copied and a folder called "GettingStarted" is created. What the Angular CLI accomplishes is

  1. a new directory has been created The creation of GettingStarted
  2. installs Angular libraries and any other dependencies that need to be downloaded.
  3. configures and installs TypeScript.
  4. Karma and Protractor are installed and set up for testing.
  5. Build the Git from scratch.

Running the Application

Enter the folder and launch either ng server or npm start to launch the application (which runs the ng serve behind the scene)
cd gettingStarted
ng serve         // or npm start  

You should now be able to view the Welcome to GettingStarted Message after opening the browser and entering the URL http://localhost:4200/

ng new options

OptionsAliasDESCRIPTION
--dry-run-dRun through without making any changes.
--force-fForces overwriting of any existing files in the project folder
--verbose-vDisplays out of the command
--collection-cSchematics to use. For more info on Schematics click here.
--inline-style-sUse inline style rather than the external StyleSheet file. does not create external Stylesheets
--inline-template-tDoes not create an external template file for the component. Specifies if the template will be in the ts file.
--view-encapsulationSpecifies the view encapsulation strategy. Three Options are available here
Emulated, Native &. None Default is Emulated
--routing Generates a routing module. If the option is not specified, it will ask for the confirmation
--prefix-pThe file extension is to be used for style files. The values available are CSS, SCSS, SASS,LESS, and Stylus. If the options are not specified, it will ask to select the appropriate style when running the command
--skip-tests-S Skip creating test spec files. This option does not seem to remove the test-related files. Check the bug report here. Use the --minimal option instead
--skip-package-jsonDo not add dependencies to package.json
--minimalInstalls the minimal set of features. Does not create test files. Creates inline style & templates


ng new example

//creates with new project with Style CSS
ng new gettingStarted --routing  --style CSS

//creates the new project with HelloWorld_root as the selector
ng new HelloWorld --routing  --style CSS -p HelloWorld

ng generate

ng generate <schematic> [options]
ng g <schematic> [options]

Components, modules, classes, pipes, and directives can all be generated with ng generate or (ng g). The list of possible artifacts is displayed in the tables below.

schematicSyntaxDESCRIPTION
appShellng g appShell [options]Generate an App shell. Read about App Shell from here
applicationng g application [options]Generates an application
classng g class [options]Generates Class file
componentng g component [options]Generates a component
directiveng g directive [options]Generates a Directive
enumng g enum [options]Generates an enum
guardng g guard [options]Generates a Guard Component
interfaceng g interface [options]Generates an Interface
libraryng g library [options]Generates a Library
moduleng g module [options]Generates a Module
pipeng g pipe [options]Generates a Pipe
serviceng g service [options]Generates a Service class
serviceWorkerng g serviceWorker [options]Generates a Service worker
universalng g universal [options]Generates a Universal

Common options

The ng g command's typical options are listed below.


OPTIONAliasDefaultDESCRIPTION
--defaults=true|falsefalseWhen true, disables interactive input prompts for options with a default
--dryRun=true|false-dfalseWhen true, run through and report activity without writing out results.
--force=true|false-ffalseWhen true, force overwriting of existing files
--help=
true|false|json|JSON
falseShows a help message for this command in the console.
--interactive=true|falsefalseWhen false, disables interactive input prompts.

Component

The component is created using the next command.

ng g component <name> [options]

Examples
ng g component Hello

What the aforementioned command does is
  • src/app is modified to include the Hello folder.
  • Create the HelloComponent in the Hello folder, along with the CSS, Spec, and Template files.
  • the root module imports the HelloComponent and adds it to the declarations array.
  • App-name> is the format used by the CSS selector. e.g., app-hello

ng g component --flat Hello does not create the folder named "hello." The src/app folder is where the component is built.

ng g component --flat hello/hello assembles the component in the folder src/app/hello

ng g component --export hello adds the component to the module's export metadata array.

ng g component --prefix=myapp hello use myapp-hello as a CSS selector.

ng g component --selector=hi --force hello uses the selection in high

generate components inside the module

ng g module account creates the account module's code.

ng g component --module=account account/hello enhances the account module with the component

The complete list of choices is provided below.

OPTIONAliasDefaultDESCRIPTION
--changeDetection= Default|OnPush-cDefaultSpecifies the change detection strategy.
--entryComponent= true|falsefalseSpecifies if the component is an entry component of declaring module.
--export=true|falsefalseSpecifies if declaring module exports the component.
--flat= true|falsefalseFlag to indicate if a directory is created.
--inlineStyle= true|false-sfalseSpecifies if the style will be in the ts file.
--inlineTemplate=true|false-tfalseSpecifies if the template will be in the ts file.
--lintFix= true|falsefalseSpecifies whether to apply lint fixes after generating the component.
--module= module-mroot moduleAllows specification of the declaring module.
--prefix= prefix-pThe prefix to apply to generated selectors.
--project= projectThe name of the project.
--selector= selectorThe selector to use for the component.
--skipImport= true|falsefalseFlag to skip the module import.
--spec= true|falsetrueSpecifies if a spec file is generated.
--styleext= styleextcssThe file extension to be used for style files
--viewEncapsulation=

Emulated| Native| None| ShadowDom
-vEmulatedSpecifies the view encapsulation strategy.

Directive

The directive is produced with the command ng g directive <name> [options]. Ng g directive, for instance, The Some.Directive.ts is produced by Some. The produced code looks like this. Additionally, it produces some directive specs.

import { Directive } from '@angular/core';
 
@Directive({
  selector: '[appSome]'
})
export class SomeDirective {
 
  constructor() { }
 
}

The folder is not created by the aforementioned operation. You can construct the directive under the folder directive by using the ng g directive/Some directive.

You can create the directive under the folder Some by using the command ng g directive --flat=false Some (folder name is the same as the directive name)

If the files already exist, you can use the --force flag to compel overwriting.

To add the directive to a module other than the root module, use the --module flag.

To alter the CSS Selector, use the --prefix or --selector flag.

The --export & --skipImport options let you add a directive to the module's exports and imports information.

The entire list of choices is provided below.

OPTIONAliasDefaultDESCRIPTION
--export=true|falsefalseSpecifies if declaring module exports the component.
--flat= true|falsetrueFlag to indicate if a directory is created.
--lintFix= true|falsefalseSpecifies whether to apply lint fixes after generating the component.
--module= module-mroot moduleAllows specification of the declaring module.
--prefix= prefix-pThe prefix to apply to generated selectors.
--project= projectThe name of the project.
--selector= selectorThe selector to use for the component.
--skipImport= true|falsefalseFlag to skip the module import.
--spec= true|falsetrueSpecifies if a spec file is generated.

Pipe

The pipe is created using the command ng generate <pipe name> [options]. Instance: ng g pipe The date.pipe.ts is generated by Date. The produced code looks like this. Additionally, it produces the date.pipe.ts.spec.ts.

import { Pipe, PipeTransform } from '@angular/core';
 
@Pipe({
  name: 'date'
})
export class DatePipe implements PipeTransform {
 
  transform(value: any, args?: any): any {
    return null;
  }
 
}

The folder is not created by the aforementioned operation. You can create the pipe under the folder pipes by using the ng g pipe pipes/Date.

You can create the pipe beneath the folder Date by using the command ng g pipe --flat=false Date (folder name is the same as the pipe name)

If the files already exist, you can use the --force flag to compel overwriting.

To add the pipe to a module other than the root module, use the --module flag.

The --export & --skipImport options let you add a directive to the module's exports and imports information.

The entire list of choices is provided below.

OPTIONAliasDefaultDESCRIPTION
--export=true|falsetrueSpecifies if declaring module exports the component.
--flat= true|falsetrueFlag to indicate if a directory is created.
--lintFix= true|falsefalseSpecifies whether to apply lint fixes after generating the component.
--module= module-mroot moduleAllows specification of the declaring module.
--project= projectThe name of the project.
--skipImport= true|falsefalseFlag to skip the module import.
--spec= true|falsetrueSpecifies if a spec file is generated.

Service

The service is generated using the command ng generate service name> [options]. Consider the ng g service. The data.service.ts and data.service.ts.spec.ts are generated by data. The command produced the sample code shown below.

import { Injectable } from '@angular/core';
 
@Injectable({
  providedIn: 'root'
})
export class DataService {
 
  constructor() { }
}

The folder is not created by the aforementioned operation. You may build the service under the folder services by using the ng g service services/Data.

You can create the service in the folder Data by using the command ng g service —flat=false Data (folder name is the same as the service name)

OPTIONAliasDefaultDESCRIPTION
--flat= true|falsetrueFlag to indicate if a directory is created.
--lintFix= true|falsefalseSpecifies whether to apply lint fixes after generating the component.
--project= projectThe name of the project.
--spec= true|falsetrueSpecifies if a spec file is generated.

class

The class is created using the command ng generate <class name> [options]. For instance, the customer.ts file in the current folder is generated by the ng g class customer. The command produced the sample code shown below.

export class Customer {
}

To create the class in the class folder, type the command ng g class/customer class.

OPTIONAliasDefaultDESCRIPTION
--project= projectThe name of the project.
--spec= true|falsetrueSpecifies if a spec file is generated.
--type=typedefaultSpecifies the type of class

Module

To generate the module, type the command ng g <module name> [options]. For instance, the command ng g module account creates the account module in the src/app/account folder. The generated code is as follows.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
 
@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class AccountModule { }

The command ng g module account --module=app creates an account module and adds it to the AppModule's imports metadata array.

account —routing=true —force ng g module. The previously created files are overwritten by the --force flag. Account-routing.module is also created when —routing=true is specified. The forChild database has the routes listed (routes)

account --force --routing=true ng g module the routes are registered with the forRoot using routingScope=Root (routes)

Module addition of components, pipes, and directives

By using the flag --module=[ModuleName] and naming the component as [ModuleName]/[ComponentnNme], you can add a component, directive, pipe, and services to a module.

As an illustration, the commands below build the account module and add the HelloComponent, SomeDirective, DataSerivce, and DatePipe to the module.

ng g module account
ng g component --module=account account/hello
ng g directive --module=account --flat=false account/Some
ng g service --module=account --flat=false account/Data
ng g pipe --module=account --flat=false account/Date

The complete list of choices is provided below.

OPTIONAliasDefaultDESCRIPTION
--flat= true|falsefalseFlag to indicate if a directory is created.
--module=module-mAllows specification of the declaring module.
--project= projectThe name of the project.
--routing=true|falsefalseGenerates a routing module.
--routingScope=Child|RootchildThe scope for the generated routing.

ng update

The angular application and its dependencies are updated to the most recent version using the ng update command. For further details, see How to Upgrade Angular to the Latest Version.

Conclusion

By enabling us to quickly establish the app and add the component, pipes, services, and directives, among other things, to the module, the Angular CLI increases productivity. There are numerous other commands in the Angular CLI that assist with building and distributing the applications, including serve, build, test, lint, and e2e. In one of the upcoming articles, we will discuss those.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post