Angular2组件开发—属性与事件(二)

事件声明 - 暴露事件源

与属性相反,事件从组件的内部流出,用来通知外部世界发生了一些事情:

在Angular2中为组件增加事件接口也非常简单:定义一个事件源/EventEmitter, 然后通过Component注解的events接口包括出来

1 //EzCard
2 @Component({
3     events:["change"]
4 })
5 class EzCard{
6     constructor(){
7         this.change = new EventEmitter();
8     }
9 }

上面的代码将组件EzCard的事件源change暴露为同名事件,这意味着在调用者EzApp组件的模板中,可以直接使用小括号语法挂接事件监听函数

1 //EzApp
2 @View({
3     template : "<ez-card (change)="onChange()"></ez-card>"
4 })

每次EzCard触发change事件时,EzApp的onChange()方法都将被调用。

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>hello,angular2</title>
 6     <script type="text/javascript" src="lib/system@0.16.11.js"></script>
 7     <script type="text/javascript" src="lib/angular2.dev.js"></script>
 8     <script type="text/javascript" src="lib/system.config.js"></script>
 9 </head>
10 <body>
11     <ez-app></ez-app>
12     
13     <script type="module">
14         import {Component,View,bootstrap,EventEmitter} from "angular2/angular2";
15         
16         //根组件 - EzApp
17         @Component({selector:"ez-app"})
18         @View({
19               directives:[EzCard],
20             template:`
21                 <div class="ez-app">
22                     <h1>EzApp</h1>
23                     <ez-card (change)="onChange($event)"></ez-card>
24                     <pre>{{evtStr}}</pre>
25                 </div>`
26         })
27         class EzApp{
28             constructor(){
29                 this.evtStr
30             }
31             onChange(evt){
32                 console.log("sth. occured");
33                 this.evtStr = JSON.stringify(evt,null,"	");
34             }
35         }       
36         
37         //具有事件接口的组件 - EzCard
38         @Component({
39             selector:"ez-card",
40             events:["change"]
41         })
42         @View({
43             template : `<div class='ez-card'>
44                     My name is <b>{{name}}</b>, 
45                     I am from <b>{{country}}</b>.</div>`
46         })
47         class EzCard{
48             constructor(){
49                 this.name = "Mike";
50                 this.country = "Sweden";
51                 this.change = new EventEmitter();
52                 //模拟触发事件
53                 setTimeout(()=>this.change.next({
54                     src:"EzCard",
55                     desc:"模拟事件"
56                 }),1000);
57             }
58         }
59                 
60         //渲染组件
61         bootstrap(EzApp);
62     </script>
63 </body>
64 </html>
原文地址:https://www.cnblogs.com/gett/p/5050865.html