#NgFor 指令ngFor
指令是通过使用可迭代的每个项作为模板的上下文来重复模板的一种方式。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 ({
selector: 'app-root',
template: `
<app-for-example *ngFor="let episode of episodes" [episode]="episode">
{{episode.title}}
</app-for-example>
`
})
export class AppComponent {
episodes = [
{ title: 'Winter Is Coming', director: 'Tim Van Patten' },
{ title: 'The Kingsroad', director: 'Tim Van Patten' },
{ title: 'Lord Snow', director: 'Brian Kirk' },
{ title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk' },
{ title: 'The Wolf and the Lion', director: 'Brian Kirk' },
{ title: 'A Golden Crown', director: 'Daniel Minahan' },
{ title: 'You Win or You Die', director: 'Daniel Minahan' },
{ title: 'The Pointy End', director: 'Daniel Minahan' }
];
}
ngFor
指令与我们看到的其他指令有不同的语法。 如果你熟悉for...of
语句,你会注意到,他们几乎相同。 ngFor
允许您指定要迭代的iterable对象,以及在范围内引用每个项的名称。 在我们的示例中,您可以看到该episode
可用于插值以及属性绑定。 该指令做一些额外的解析,所以当它扩展到模板形式,它看起来有点不同:
1 | ({ |
请注意,模板元素上有一个奇怪的let-episode属性。 ngFor指令在其范围内提供一些变量作为上下文。 let-episode是一个上下文绑定,这里它接受迭代的每个项的值。
NgFor
还提供了可以被局部变量别名的其他值:
1 | ({ |
##trackBy
通常ngFor
用于迭代具有唯一ID字段的对象列表。 在这种情况下,我们可以提供一个trackBy
函数,帮助Angular跟踪列表中的项目,以便它可以检测哪些项目已添加或删除,并提高性能。
Angular 2将通过引用来尝试和跟踪对象,以确定应该创建和销毁哪些项目。 然而,如果你用一个新的对象源代替列表,也许是一个API请求的结果,我们可以通过告诉Angular 2如何跟踪事情来获得一些额外的性能。
例如,如果Add Episode
按钮是要发出请求并返回新的剧集列表,我们可能不想销毁并重新创建列表中的每个项目。 如果剧集有唯一的ID,我们可以添加一个trackBy
函数:
1 | ({ |
要了解这会如何影响ForExample
组件,我们向它添加一些 console。1
2
3
4
5
6
7
8
9
10export class ForExampleComponent {
() episode;
ngOnInit() {
console.log('component created', this.episode)
}
ngOnDestroy() {
console.log('destroying component', this.episode)
}
}
当我们查看示例时,当我们点击Add Episode
时,我们可以看到控制台输出,指示只有一个组件被创建 - 用于新添加到列表中的项目。
但是,如果我们从*ngFor
中删除trackBy
- 每次我们单击按钮,我们将看到组件中的项目被销毁和重新创建。