初识Angular2

初识Angular2

写一个Angular2的Hello World应用相当简单,分三步走:

1. 引入Angular2预定义类型

  1. import {Component,View,bootstrap} from "angular2/angular2";

import是ES6的关键字,用来从模块中引入类型定义。在这里,我们从angular2模块库中引入了三个类型: Component类、View类和bootstrap函数。

2. 实现一个Angular2组件

实现一个Angular2组件也很简单,定义一个类,然后给这个类添加注解:

 

    1. @Component({selector:"ez-app"})
    2. @View({template:"<h1>Hello,Angular2</h1>"})
    3. class EzApp{}

class也是ES6的关键字,用来定义一个类。@Component和@View都是给类EzApp附加的元信息, 被称为注解/Annotation。

@Component最重要的作用是通过selector属性(值为CSS选择符),指定这个组件渲染到哪个DOM对象上。 @View最重要的作用是通过template属性,指定渲染的模板。

3. 渲染组件到DOM

将组件渲染到DOM上,需要使用自举/bootstrap函数:

  1. bootstrap(EzApp);

这个函数的作用就是通知Angular2框架将EzApp组件渲染到DOM树上。

简单吗?我知道你一定还有疑问,别着急,我们慢慢把缺失的知识点补上!

把@Component的selector属性改为"ez-app",还应该改哪里可以获得和示例同样的结果?
 
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>hello,angular2</title>
    <!--模块加载器-->
    <script type="text/javascript" src="lib/system@0.16.11.js"></script>
    <!--Angular2模块库-->
    <script type="text/javascript" src="lib/angular2.dev.js"></script>
    <script>
        //设置模块加载规则
        System.baseURL = document.baseURI;
        System.config({
            map:{traceur:"lib/traceur"},
            traceurOptions: {annotations: true}
        });
    </script>        
</head>
<body>
    <!--组件渲染锚点-->
    <my-app></my-app>
    
    <!--定义一个ES6脚本元素-->
    <script type="module">
        //从模块库引入三个类型定义
        import {Component,View,bootstrap} from "angular2/angular2";
        
        //组件定义
        @Component({selector:"my-app"})
        @View({template:"<h1>Hello,Angular2</h1>"})
        class EzApp{}       
        
        //渲染组件
        bootstrap(EzApp);
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/yanyanhappy/p/5667253.html