ngFor directive
This is the documentation for Angular 6.
You can switch to the latest version Angular 10.
You can switch to the latest version Angular 10.
NgForOf is a repeater directive — a way to present a list of items. You define a block of HTML that defines how a single item should be displayed. You tell Angular to use that block as a template for rendering each item in the list.
Source
<div *ngFor="let item of items">
{{ item }}
</div>
export class AppComponent {
items = ['One', 'Two', 'Three'];
}
Result
One
Two
Three
You can also apply an NgForOf
to a component element, as in this demo:
Source
app.component.ts
<my-component *ngFor="let item of items"
[item]="item">
</my-component>
app.component.ts
export class AppComponent {
items = ['One', 'Two', 'Three'];
}
my.component.html
<div>{{ item }}</div>
my.component.ts
export class MyComponent {
@Input() item: string;
}
Result
One
Two
Three
Local Variables
NgForOf
provides several exported values that can be aliased to local variables:
$implicit: T
: The value of the individual items in the iterable (ngForOf
).ngForOf: NgIterable<T>
: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async
).index: number
: The index of the current item in the iterable.first: boolean
: True when the item is the first item in the iterable.last: boolean
: True when the item is the last item in the iterable.even: boolean
: True when the item has an even index in the iterable.odd: boolean
: True when the item has an odd index in the iterable.
Source
<li *ngFor="let item of itemsObservable | async as items; index as i; first as isFirst">
{{i}}/{{items.length}}. {{ item }} <span *ngIf="isFirst">default</span>
</li>
export class AppComponent {
itemsObservable = from([['One', 'Two', 'Three']]);
}
Result
*ngFor with trackBy
The NgForOf
directive may perform poorly, especially with large lists. A small change to one item, an item removed, or an item added can trigger a cascade of DOM manipulations.
Angular can avoid this churn with trackBy
. Add a method to the component that returns the value NgForOf
should track.
Source
<div *ngFor="let item of items; trackBy: trackById">
({{item.id}}) {{item.title}}
</div>
export class AppComponent {
items = [
{id: 1, title: 'One'},
{id: 2, title: 'Two'},
{id: 3, title: 'Three'},
];
trackById(index: number, item: any): number {
return item.id;
}
}
Result
(1) One
(2) Two
(3) Three
Links & Tutorials