前端之Angular2实战:内置指令中的ngFor

Angular2 内置了许多新的指令,其中NgFor就是用来进行替换旧有的ng-repeat标签。关于Angular2开发进度可以查看Is Angular 2 Ready?,关于笔者的相关代码可以查看这里。

Angular1中展示列表数据的方式如下:


  • {{$index}} {{item}}

而如果使用ng-for的话,如下所示:


  • {{i}} {{item}}

Angular2引入了很多新的语法,其中*ng-for中的*是Angular2中template语法的缩写,如果是全部的话,应该为:


在正常的开发中,基本上不会用到这种全语法,不过知道*表达式的意义还是很有必要的。template的作用在于防止浏览器读取或者执行内部标签,这样就能够保证Angular2安全地生成模板而不需要担心被XSS等。另一个常用的表达式为#item of items;,#表达式会创建一个局部变量以供在template内部使用。

一个完整的ngFor指令用法如下所示:

  • Component

//Typescript
class DisplayComponent {
  myName: string;
  names: Array;
  constructor() {
    this.myName = "Alice";
    this.names = ["Aarav", "Martín", "Shannon", "Ariana", "Kai"];
  }
}
  • View

//Typescript
import {Component, View, bootstrap, NgFor} from 'angular2/angular2';
@View({
  template: `
  

My name: {{ myName }}

Friends:

  • {{ name }}
`, directives: [NgFor] })

当然,也可以将数据的获取写成依赖注入的模式,譬如我们创建了一个Service为:

class FriendsService {
  names: Array;
  constructor() {
    this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
  }
}

那么在Component中就需要引入:

@Component({
  ...
  appInjector: [FriendsService]
})
class DisplayComponent {
  myName: string;
  names: Array;
  constructor(friendsService: FriendsService) {
    this.myName = 'Alice';
    this.names = friendsService.names;
  }
}

关于Angular2中依赖注入的解释与使用可以查看本系列其他文章。

你可能感兴趣的:(angular.js,frontend)