angular2---ngFor指令及其简化

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标签,直接把指令写到模板的容器标签上。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值