神刀安全网

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

Angular 2 CLI  aka Command Line Interface is developed to get started quickly for building Angular 2 apps, especially when the entire community felt that setting up Angular 2 development environment was cumbersome.

With introduction of Angular CLI, it’s now easier than ever to create, run builds, do E2E (end to end) tests, run apps and deploy Angular 2 application.

In this article, I will build a very basic Angular 2 application exclusively using CLI. So lets started.

What we will learn here?

  1. Installing Angular 2 CLI using NPM.
  2. Creating an Angular 2 application using command line interface
  3. Examine CLI created project structure.
  4. Serve or Run Angular 2 application.
  5. Create models and services to work with data.
  6. Create Dashboard page using router

Installing Angular 2 CLI using NPM

Ensure you have latest NPM and Node installed on your machine. After that run this command to install Angular 2 CLI globally. After installation just verify as shown in figure

npminstall -g angular-cli 

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

Angular CLI version

Creating an Angular 2 application using command line interface

We will be creating a simple “OurPlanets” application displaying list of our solar system planets

Run the below command in prompt to create new Angular 2 app. “ OurPlanets ” is application, the –prefix option tells us that “ Planets ” will be added as prefix for project files.

ngnew OurPlanets --prefixPlanets 

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

CLI – ng New Command

  1. CLI command – ng new to create application
  2. List of files created using CLI command
  3. The newly created application is now GIT repository by default.
  4. As the package.json is already created, CLI command restore the packages. It takes few minutes to restore packages.

Examine CLI created “ OurPlanets ” project structure in Visual Studio Code

Open Visual Studio code, load this project. We will check out project structure got created for us.

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

“OurPlanets” project structure in VS Code

  1. Config ” folder containing configuration related environment, karma, protractor
  2. e2e ” folder containing test files, configurations for performing end to end testing.
  3. node_modules ” folder contains all packages restored as per package.json
  4. public ” folder is location to hold images, static assets
  5. src ” folder is the main application development folder containing template HTML files, TS files, components.
  6. packages.json ” essential file which contains reference to all packages needed for running Angular 2 app. See .gitignore file also. Automatically “ OurPlanets ” application is GIT repo, which we can push it if needed.

Isn’t it amazing just by running “ng new” command of Angular 2 CLI gives us so much stuff to get started.

Serve or run “OurPlanets” Angular 2 apps

Now that we have app with all dependencies, build it and run as shown in figure.

ngbuild 

ngserve 

Note: ng build command creates “dist/”, a folder containing compiled, minified (if applied) your Angular 2 application.

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

CLI build/ serve creates dist folder

  • ng serve command runs and listens on location, but doesn’t open any browser. If you wish you can use lite-server for it.
  • “public” folder has semantic.min.css and themes folder which are moved to “dist” folder. Its not provided by Angular 2 CLI steps, I have added explicitly.
Angular 2 CLI – Build Angular 2 apps using Command Line Interface

Angular 2 app running using ng serve

Create Planets model and PlanetService using CLI

As “ OurPlanets ” application is about solar system planets, it’s time to create model and service to get planets list and its details in form of planet.

Model refers to class structure containing properties just like C#, Java.

Run the following commands to create “planet.model” model class and “planet.service” service.

//create planet model nggenerateclass shared/planetsmodel   //create planet service nggenerateserviceshared/planets 

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

CLI command to create planet model & service

Note: class generating command lets have suffix with ‘model’, service generating command creates file with ‘service’ suffix.

CLI also generates spec TS files used for unit testing

Open planets.model.ts file & copy below code, its really simple class with four fields.

export class Planets {     position: number;     name: string;     distanceFromSun: number;     description: string; } 

Open planets.service.ts file to copy below code; it imports ‘planets.model’, getPlanets method which returns list of planets data. Nothing fancy, but still good enough

import { Injectable } from '@angular/core'; import { Planets } from './planets.model';   @Injectable() export class PlanetsService {     constructor() {}   getPlanets(): Promise<Planets[]>{     return Promise.resolve(PLANETSDATA);   } }   const PLANETSDATA: Planets[] = [   {position: 1, name: 'Mercury',distanceFromSun: 58,description: '88 earth days to orbit the sun' },   {position: 2, name: 'Venus',distanceFromSun: 108,  description: '225 earth days to orbit the sun' },   {position: 3, name: 'Earth',distanceFromSun: 150,  description: '365 earth days to orbit the sun' },   {position: 4, name: 'Mars',distanceFromSun: 228,  description: '686 earth days to orbit the sun' },   {position: 5, name: 'Jupiter',distanceFromSun: 778,  description: '12 earth years to orbit the sun' },   {position: 6, name: 'Saturn',distanceFromSun: 886,  description: '29 earth years to orbit the sun' },   {position: 7, name: 'Uranus',distanceFromSun: 1800,  description: '84 earth years to orbit the sun' },   {position: 8, name: 'Neptune',distanceFromSun: 2800,  description: '165 earth years to orbit the sun' } ]; 

Create Dashboard page using Router

Until now, we created Angular 2 app, added planets.model and planets.service. It’s time to create router. Run the following command to create and later see the magic !!

nggenerateroutedashboard 

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

CLI command to create route

The above shows only files created by ng generate route command, but CLI magic takes place in following files

  1. our-planets.component.html — router-outlet is added.
  2. system-config.ts — Dashboard is added to Angular 2 barrels (It helps to keep clean component code)
  3. our-planets.components.ts – Major magic happens here, Angular 2 CLI adds required router imports, adds directives, providers in @component, sets path in @Routes. Check out git difference of this file.
Angular 2 CLI – Build Angular 2 apps using Command Line Interface

Git diff of our-planets.component.ts

Now we are almost there, we have Angular 2 app setup with components, a sample service with model, a router to display planets. Lets add up all code required file by file.

our-planets.component.ts

import { Component } from '@angular/core'; import { DashboardComponent } from './+dashboard'; import { Routes , ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router'; import { PlanetsService } from './shared';   @Component({   moduleId: module.id,   selector: 'our-planets-app',   templateUrl: 'our-planets.component.html',   styleUrls: ['our-planets.component.css'],   directives: [ROUTER_DIRECTIVES],   providers: [ROUTER_PROVIDERS, PlanetsService] }) @Routes([   {path: '/dashboard', component: DashboardComponent} ]) export class OurPlanetsAppComponent {   title = 'Welcome to Solar System Planets !!'; } 

our-planets.component.html

<h3class="ui block header">   {{title}} </h3> <nav>   <a [routerLink]="['dashboard']">Dashboard</a> </nav> <router-outlet></router-outlet> 

dashboard.component.html – Displays UI on click on Dashboard link

<br> <divclass="ui cards" *ngFor="let planet of planetsList"> <divclass="card" >     <divclass="content">     <a class="header">{{planet.name}}</a>     <divclass="meta">       <spanclass="date">Position {{planet.position}} fromSUN</span>     </div>     <divclass="description">       {{planet.description}}     </div>   </div>   </div> </div> 

dashboard.component.ts – imports Planets, PlanetsService to get list of planets

import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Planets, PlanetsService } from '../shared';   @Component({   moduleId: module.id,   selector: 'planets-dashboard',   templateUrl: 'dashboard.component.html',   styleUrls: ['dashboard.component.css'] }) export class DashboardComponent implements OnInit {   planetsList: Planets[] = [];   constructor(     private _planetservice: PlanetsService,     private _router: Router) {}     ngOnInit() {     this._planetservice.getPlanets().then(planets => this.planetsList = planets);   }   } 

We finished our sample Angular 2 app coding, now lets run ng build and ng serve to see it working. We can do live editing with CLI

Angular 2 CLI – Build Angular 2 apps using Command Line Interface

Our Planets up and running

There are many more Angular 2 CLI commands with interesting options, will explore them.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Angular 2 CLI – Build Angular 2 apps using Command Line Interface

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址