寫一個Angular2的Hello World應用至關簡單,分三步走:javascript
1. 引入Angular2預約義類型html
1 import {Component,View,bootstrap} from "angular2/angular2";
import是ES6的關鍵字,用來從模塊中引入類型定義。在這裏,咱們從angular2模塊庫中引入了三個類型: Component類、View類和bootstrap函數。java
2. 實現一個Angular2組件bootstrap
實現一個Angular2組件也很簡單,定義一個類,而後給這個類添加註解:angular2
1 @Component({selector:"ez-app"}) 2 @View({template:"<h1>Hello,Angular2</h1>"}) 3 class EzApp{}
class也是ES6的關鍵字,用來定義一個類。@Component和@View都是給類EzApp附加的元信息, 被稱爲註解/Annotation。app
@Component最重要的做用是經過selector屬性(值爲CSS選擇符),指定這個組件渲染到哪一個DOM對象上。 @View最重要的做用是經過template屬性,指定渲染的模板。框架
3. 渲染組件到DOM函數
將組件渲染到DOM上,須要使用自舉/bootstrap函數:spa
1 bootstrap(EzApp);
這個函數的做用就是通知Angular2框架將EzApp組件渲染到DOM樹上。code
注:HTML DOM是HTML Document Object Model(文檔對象模型)的縮寫,HTML DOM則是專門適用於HTML/XHTML的文檔對象模型。熟悉軟件開發的人員能夠將HTML DOM理解爲網頁的API。它將網頁中的各個元素都看做一個個對象,從而使網頁中的元素也能夠被計算機語言獲取或者編輯。 例如Javascript就能夠利用HTML DOM動態地修改網頁。HTML DOM 定義了訪問和操做HTML文檔的標準方法。HTML DOM 把 HTML 文檔呈現爲帶有元素、屬性和文本的樹結構(節點樹)。
例:把@Component的selector屬性改成"ez-app",還應該改哪裏能夠得到和示例一樣的結果?
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>hello,angular2</title> 6 <!--模塊加載器--> 7 <script type="text/javascript" src="lib/system@0.16.11.js"></script> 8 <!--Angular2模塊庫--> 9 <script type="text/javascript" src="lib/angular2.dev.js"></script> 10 <script> 11 //設置模塊加載規則 12 System.baseURL = document.baseURI; 13 System.config({ 14 map:{traceur:"lib/traceur"}, 15 traceurOptions: {annotations: true} 16 }); 17 </script> 18 </head> 19 <body> 20 <!--組件渲染錨點--> 21 <my-app></my-app> 22 23 <!--定義一個ES6腳本元素--> 24 <script type="module"> 25 //從模塊庫引入三個類型定義 26 import {Component,View,bootstrap} from "angular2/angular2"; 27 28 //組件定義 29 @Component({selector:"my-app"}) 30 @View({template:"<h1>Hello,Angular2</h1>"}) 31 class EzApp{} 32 33 //渲染組件 34 bootstrap(EzApp); 35 </script> 36 </body> 37 </html>
修改成:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>hello,angular2</title> 6 <!--模塊加載器--> 7 <script type="text/javascript" src="lib/system@0.16.11.js"></script> 8 <!--Angular2模塊庫--> 9 <script type="text/javascript" src="lib/angular2.dev.js"></script> 10 <script> 11 //設置模塊加載規則 12 System.baseURL = document.baseURI; 13 System.config({ 14 map:{traceur:"lib/traceur"}, 15 traceurOptions: {annotations: true} 16 }); 17 </script> 18 </head> 19 <body> 20 <!--組件渲染錨點--> 21 <ez-app></ez-app> 22 23 <!--定義一個ES6腳本元素--> 24 <script type="module"> 25 //從模塊庫引入三個類型定義 26 import {Component,View,bootstrap} from "angular2/angular2"; 27 28 //組件定義 29 @Component({selector:"ez-app"}) 30 @View({template:"<h1>Hello,Angular2</h1>"}) 31 class EzApp{} 32 33 //渲染組件 34 bootstrap(EzApp); 35 </script> 36 </body> 37 </html>