📅  最后修改于: 2023-12-03 15:03:10.615000             🧑  作者: Mango
ngFor
is a directive in Angular that is used to display a collection of data in the template. It is mostly used with arrays, but it can be used with other collection types as well.
ngFor
works by iterating over the items in the collection and creating a template instance for each item. The template instance can then be manipulated to display the data in a variety of ways.
The basic syntax of ngFor
is as follows:
<ng-container *ngFor="let item of items">
{{ item }}
</ng-container>
In this example, we use *ngFor
to iterate over the items
array. The let
keyword is used to create a variable item
that will hold the value of the current item in the iteration. We then display the value of item
using interpolation ({{ item }}
).
ngFor
can also be used to iterate over objects, but it requires some additional syntax. Here's an example:
<ng-container *ngFor="let item of items | keyvalue">
Key: {{ item.key }}, Value: {{ item.value }}
</ng-container>
In this example, we use the keyvalue
pipe to iterate over the properties of the items
object. The key
and value
properties of each property are then displayed using interpolation.
When using ngFor
, Angular creates and destroys elements as the collection changes. This can be inefficient, especially if the items in the collection don't change often. To improve performance, you can add a trackBy
function to ngFor
that tells Angular how to identify items in the collection. Here's an example:
<ng-container *ngFor="let item of items; trackBy: trackByFunction">
{{ item }}
</ng-container>
In this example, we've added a trackBy
function called trackByFunction
. This function takes an item from the collection and returns a unique identifier for that item. Angular uses this identifier to keep track of the items in the collection, and only creates and destroys elements when necessary.
ngFor
is a powerful directive in Angular that allows you to display collections of data in a flexible and efficient way. Whether you're working with arrays, objects, or other collection types, ngFor
has you covered.