app.ts
import {Component} from '@angular/core';
import {bootstrap} from '@angular/platform-browser-dynamic';
@Component({
selector: 'app',
templateUrl: './app.html',
})
class App {
todos:string[];
name:string;
constructor() {
this.name = "John";
this.todos = ['Buy milk', "Save the world"];
}
}
bootstrap(App);
组件的构建函数里增加了一个todos列表。
app.html
<h1>Hello {{name}}!</h1>
<p>
Here's list of the things you need to do:
</p>
<ul>
<template ngFor let-todo [ngForOf]="todos">
<li>{{todo}}</li>
</template>
</ul>
template标签内部可以放html片段,它可以保证里面的内容不会被浏览器渲染出来。如果angular2的DOM编译器没有处理完DOM树,屏幕上就只能看到h1、p和ul元素,ul元素内部没有任何列表项。
template标签上出现了ngFor指令,它与angularjs中的ng-repeat一样,但它支持更多语法特性。注意ngForOf属性外面包着一个方括号,含义是包含在方括号中的属性是一个需要执行的表达式。
[ngFor]的值作为表达式执行之后会返回一个集合,我们通过var-todo这种语法来告诉angular:我们需要创建一个新的变量叫做todo,然后在遍历集合的过程中,其中的每一个元素都要赋值给这个新建的变量。
上述语法写起来非常的啰嗦,angular2提供了一种更简便的语法糖:在angular2中很多指令需要用到template标签,如ngForOf、ngIf、ngSwitch,都有对应的简化语法,我们可以在指令前面加一个*号作为前缀,而不需要把整个template标签都完整敲出来,如下:
<h1>Hello {{name}}!</h1>
<p>
Here's list of the things you need to do:
</p>
<ul>
<li *ngFor="let todo of todos">
{{todo}}
</li>
</ul>
使用*号可以扔掉template标签,直接把指令写到模板的容器标签上。