How to use ngFor in Angular
Rendering dynamic lists is fundamental in Angular applications, especially for dashboards, data tables, and any component displaying arrays of data.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented ngFor in countless Angular components including data tables, navigation menus, and dashboard widgets.
From my expertise, the most efficient approach is to use the *ngFor
structural directive with proper TypeScript typing.
This method provides clean template syntax and excellent performance when combined with trackBy functions.
Use *ngFor
structural directive to iterate over arrays and render list items.
<li *ngFor="let item of items">{{ item.name }}</li>
The *ngFor
directive creates a template for each item in the array, automatically handling DOM updates when the array changes. The let item of items
syntax defines a template variable item
that represents the current array element. Angular efficiently updates only the changed DOM elements when the array is modified. For complex objects, access properties with dot notation like item.name
or item.id
to display specific data fields.
Best Practice Note:
This is the same approach we use in CoreUI Angular components for rendering navigation items and table rows.
For large lists, add trackBy: trackByFn
to improve performance by helping Angular identify which items have changed.