Angular2组件开发—模板语法,六

#var - 局部变量

有时模板中的不同元素间可能需要互相调用,Angular2提供一种简单的语法将元素 映射为局部变量:添加一个以#或var-开始的属性,后续的部分表示变量名, 这个变量对应元素的实例。

在下面的代码示例中,我们为元素h1定义了一个局部变量v_h1,这个变量指向 该元素对应的DOM对象,你可以在模板中的其他地方调用其方法和属性:

1 @View({
2     template : `
3         <h1 #v_h1>hello</h1>
4         <button (click)="#v_h1.textContent = 'HELLO'">test</button>
5     `
6 })

如果在一个组件元素上定义局部变量,那么其对应的对象为组件的实例:

1 @View({
2     directives:[EzCalc],
3     template : "<ez-calc #c=""></ez-calc>"
4 })

在上面的示例中,模板内的局部变量c指向EzCalc的实例。

例如:

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>template - local var</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} from "angular2/angular2";
15 
16         @Component({selector:"ez-app"})
17         @View({
18             template:`    
19                 <h1>
21                     I choose 
22                     <b #v_who>WHO?</b>
23                 </h1>
24                 <button (click)="v_who.textContent = 'Jason'">Jason</button>
25                 <button (click)="v_who.textContent = 'Mary'">Mary</button>
26                 <button (click)="v_who.textContent = 'Linda'">Linda</button>
27                 <button (click)="v_who.textContent = 'Lincoln'">Lincoln</button>
28                 <button (click)="v_who.textContent = 'Jimmy'">Jimmy</button>
29                 <button (click)="v_who.textContent = 'Albert'">Albert</button>
30                `
31         })
32         class EzApp{}
33                 
34         bootstrap(EzApp);
35 
36     </script>
37 </body>
38 </html>