angular2.0学习日记1

使用NG2之前需要安装node以及Npm环境,并到node下下载ng2所需要得文件,具体配置请到https://angular.cn/docs/ts/latest/quickstart.html按照提示操作,安装完毕并创建后各种目录后,正式开始编写第一个HelloWordl;

ng2是基于typescript,文件以ts结尾代表typesript文件,启动Npm start后,node会监视目录下的文件变得将ts编译为js文件

首先创建根模块文件app/app.module.ts, 每个Angular2的应用都至少有一个模块即跟模块。

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

@NgModule({

imports: [ BrowserModule ]

})

export class AppModule { }

//import2行表示从目录中引入我们所需得文件,import是ES6关键字,经过编译后会被转化为ES5的require,形式如下:

//var core = require('@angular/core');

//var bsmodule = require('@angular/platform-browser');

//@NgModule:意思为告诉Angular如何去编译和运行代码。模块内部可以包含组件、指令、管道,并且可以将它们的访问权限声明为公有,以使外部模块的组件可以访问和使用到它们;

NgModule的主要属性如下:北京联盟 http://www.010lm.com/

  • declarations:模块内部Components/Directives/Pipes的列表,声明一下这个模块内部成员
  • providers:指定应用程序的根级别需要使用的service。(Angular2中没有模块级别的service,所有在NgModule中声明的Provider都是注册在根级别的Dependency Injector中)
  • imports:导入其他module,其它module暴露的出的Components、Directives、Pipes等可以在本module的组件中被使用。比如导入CommonModule后就可以使用NgIf、NgFor等指令。
  • exports:用来控制将哪些内部成员暴露给外部使用。导入一个module并不意味着会自动导入这个module内部导入的module所暴露出的公共成员。除非导入的这个module把它内部导入的module写到exports中。
  • bootstrap:通常是app启动的根组件,一般只有一个component。bootstrap中的组件会自动被放入到entryComponents中。
  • entryCompoenents: 不会再模板中被引用到的组件。这个属性一般情况下只有ng自己使用,一般是bootstrap组件或者路由组件,ng会自动把bootstrap、路由组件放入其中。 除非不通过路由动态将component加入到dom中,否则不会用到这个属性

项目是运行在浏览器中的 Web 应用,所以根模块需要从 @angular/platform-browser 中导入 BrowserModule 并添加到 imports 数组中;

//export 也是es6的关键字,表示导出,以使得其他组件或者模块可以导入(import);

接着创建根组件app/app.component.ts

import { Component } from '@angular/core';

@Component({

selector: 'my-app',

template: '<h1>hello wordl</h1>'

})

export class AppComponent { }

//@Component表示将一份数据关联到导出的AppComponent,虽然此处AppComponent导出内容为空,但实际上@Component中的内容由于与之关联,因此里面的selector: 'my-app',

template: '<h1>My First Angular 2 App</h1>'实际上也一起导出,可供外部使用了;

//selector: 'my-app' 指my-app标签,即<my-app></my-app>;

select还可以使用属性以及类,如selector:".example"或者selector:"[ example ]",代表类名为或者属性为example的标签;

//template:要渲染的模板,如<h1>12345</h1>则表示将上面对应的seletor的innerhtml渲染为<h1>12345</h1>,

temlpate为联写法,还可以写为外部引入写法:templateUrl:"../index.html", 这样写需要先定义好一个html文件,其内容为<h1>12345</h1>,并引入;

组件写好后,需要在根模块下将写好的组件引入,在app/app.module.ts下import { AppComponent } from './app.component';

并修改:@NgModule({imports: [ BrowserModule ]

,declarations: [ AppComponent ],

bootstrap: [ AppComponent ]

}

)

最后添加新文件main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

const platform = platformBrowserDynamic();

platform.bootstrapModule(AppModule);

至此就可以启动应用了,在npm下输入npm start等待几秒即可