跳至主要内容

Getting started wtih Angualr 2:part 1

Hello, Angular 2

After couples of Betas and 7 RCs, Angular 2 GA is finally available for production.
Angular 2 is a compoenent based frontend framework, and it is completely refactored from Angular 1. You can consider it as a new framework. For those whose have used AngularJS 1.x in projects, Angular team provides official Upgrade Guide from Angular 1.x.
To kickstart an Angular 2 project, Angular provides Angular CLI. Angular CLI is a command line tooling to create a new project skeleton and generate Angular 2 facilities thus speed up Angular2 development.
In order to get started with Angular 2, you could have to learn the basic knowledge of Typescript language and RxJS.

Install Angular CLI

I assume you have installed the latest NodeJS 7.x and the latest NPM 3.x or above.
Install Angular CLI in system globally via npm install command.
Note: Angular CLI 1.0.0-beta.28.3 or later, the package name(angular-cli) was renamed to @angular/cli.
npm i -g @angular/cli
When it is done, a new command named ng should be available in the system path. Under windows system, open a new terminal and verify it.
ng --version
You should see the output info similar the following.
>$ ng --version                                                               

                             _                           _  _                
  __ _  _ __    __ _  _   _ | |  __ _  _ __         ___ | |(_)               
 / _` || '_ \  / _` || | | || | / _` || '__|_____  / __|| || |               
| (_| || | | || (_| || |_| || || (_| || |  |_____|| (__ | || |               
 \__,_||_| |_| \__, | \__,_||_| \__,_||_|          \___||_||_|               
               |___/                                                         
@angular/cli: 1.0.0-beta.32.3                                                
node: 7.5.0                                                                  
os: win32 x64                                                                
@angular/common: 2.2.1                                                       
@angular/compiler: 2.2.1                                                     
@angular/compiler-cli: 2.2.1                                                 
@angular/core: 2.2.1                                                         
@angular/forms: 2.2.1                                                        
@angular/http: 2.2.1                                                         
@angular/platform-browser: 2.2.1                                             
@angular/platform-browser-dynamic: 2.2.1                                     
@angular/platform-server: 2.2.1  

Create a new project

Create a new Angular2 project via ng new command.
ng new angular2-sample
Here angular2-sample is the project name, after it is done, there is a folder named angular2-sample will be created.
This command will try to perform the following tasks.
  1. Create a new folder and generate the project skeleton codes from Angular CLI internal template.
  2. Run npm install in the background to download all dependencies for Angular CLI tooling and those declared in the package.json file for this project.
This progress will take some seconds or minutes. Please be patient and have a coffee break to wait for a while.
Alternatively, you can create a new folder(eg. angular2-sample), and enter this folder and use ng init to initialize the project skeleton files.
Enter the new project was just created.
cd angular2-sample
You will see the following structure in the project root folder.
1-hello-tree.png
karma and protractor is configuration files for unit tesing and end to end testing.
dist folder will contain the final build result.
node_modules includes the downloaded NPM dependencies defined in package.json and Angular CLI internally.
src holds the source codes of this project, all our development codes will be placed into this folder.
e2e includes the end to end testing codes for this project.
tslint is the Typescript grammar checking configuration.
You can run ng help to get all available commands and command options.

Run the project

Execute the following command to run this project.
ng serve
or
npm run start
NOTE: Under Windows system, if you see some errors in the terminal when run this command, try to switch to Administrator role and run again.
You will see info similar with the following in your terminal window.
Time: 56008ms                                                
           Asset       Size  Chunks             Chunk Names  
  main.bundle.js    2.83 MB    0, 2  [emitted]  main         
styles.bundle.js    10.2 kB    1, 2  [emitted]  styles       
       inline.js    5.53 kB       2  [emitted]  inline       
        main.map    2.89 MB    0, 2  [emitted]  main         
      styles.map    14.1 kB    1, 2  [emitted]  styles       
      inline.map    5.59 kB       2  [emitted]  inline       
      index.html  475 bytes          [emitted]               
Child html-webpack-plugin for "index.html":                  
         Asset     Size  Chunks       Chunk Names            
    index.html  2.81 kB       0                              
webpack: bundle is now VALID.  
By default the application will run on port 4200.
Open your browser and navigate http://localhost:4200.
1-start.png

Say Hello to Angular 2

Open src\app\app.component.ts file.
Add another property, it looks like:
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
  greeting: string = '';
}
AppComponent is the entry component for this application. We will discuss it in details.
In the template file, add input field greeting.
<input type="text" [(ngModel)]="greeting">
<br/>
Hello, {{greeting}}
Save these files, the application should be reloaded if it is running. Try to type some text in the input box, the text below this input box will be updated automaticially.
Alternatively, Angular team provides some repositories to start an Angular 2 project quickly.
  1. The official quickstart is available for the official quickstart tutorial, and provides the essential resource of starting a new Angular 2 project.
  2. The official Angular2 seed provides the simplest project skeleton, and it supports webpack and systemjs.
In this post, we have learned how to create a new project via ng new command, and how to run this project via ng serve. In the next post, we will write some real codes.

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =...

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert...

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public clas...