📜  ngfor (1)

📅  最后修改于: 2023-12-03 15:03:10.626000             🧑  作者: Mango

ngFor in Angular

One of the most powerful and useful directives in Angular is ngFor. It allows you to iterate over a collection of items and render them dynamically in your application.

Basic Usage

ngFor is used by combining it with a template. The template should include the *ngFor directive and use it to iterate over the collection.

Here's an example of how to use ngFor to render a list of items in your component's template:

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

In the code above, items is an array of items that you want to render in the list. ngFor is used to iterate over the array and render a new li element for each item.

Using ngFor with index

Sometimes it's useful to know the index of the current item in the loop. ngFor makes this easy by providing an index variable:

<ul>
  <li *ngFor="let item of items; let i = index">{{ i + 1 }} - {{ item }}</li>
</ul>

In the code above, i is the index variable, which is incremented for each item in the loop. The +1 is added to the index to make it more human-readable (since indexes start at 0).

Iterating over Objects

ngFor works with arrays, but it can also iterate over properties of an object using the keyvalue pipe:

<ul>
  <li *ngFor="let item of myObj | keyvalue">{{ item.key }}: {{ item.value }}</li>
</ul>

In the code above, myObj is an object with properties that you want to render as a list. The keyvalue pipe converts the object to an array of key-value pairs.

Advanced Usage

ngFor can also be used with complex data structures, such as nested arrays or objects. In these cases, you may need to use nested ngFor loops or additional conditional logic in your template.

<div *ngFor="let group of groups">
  <h2>{{ group.name }}</h2>
  <ul>
    <li *ngFor="let item of group.items">{{ item }}</li>
  </ul>
</div>

In the code above, groups is an array of objects that each contain a name property and an items array. ngFor is used twice to render the groups and their items.

Conclusion

ngFor is a versatile and powerful directive in Angular that can be used to create dynamic templates that respond to changes in data. By mastering the basic and advanced usage of ngFor, you can create complex and responsive applications that provide a great user experience.