Performance: *ngFor for list rendering
*ngFor affects how many DOM elements are created and updated, impacting rendering speed and responsiveness when displaying lists.
<div *ngFor="let item of items; trackBy: trackById">{{item.name}}</div> trackById(index: number, item: any): any { return item.id; }
<div *ngFor="let item of items">{{item.name}}</div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| *ngFor without trackBy | Destroys and recreates all nodes on list change | N reflows for N items | High paint cost due to full redraw | [X] Bad |
| *ngFor with trackBy | Reuses existing nodes, updates only changed items | Single or minimal reflows | Low paint cost, partial redraw | [OK] Good |
*ngFor="let item of items" do in a template?*ngFor directive is used to repeat an HTML element for each item in a list.let item of items means for each element in the list 'items', create a copy of the element with 'item' as the current element.*ngFor to loop over a list named fruits?*ngFor uses let variable of list to iterate over the list.*ngFor="let fruit of fruits" uses let fruit of fruits, which matches the correct syntax. *ngFor="let fruit in fruits" uses 'in' which is incorrect in Angular templates.items = ['apple', 'banana', 'cherry'];
<ul>
<li *ngFor="let fruit of items">{{ fruit }}</li>
</ul>*ngFor to create a <div *ngFor="item of items">{{ item }}</div>*ngFor="let item of items".users = [{name: 'Alice'}, {name: ''}, {name: 'Bob'}, {name: null}];*ngFor to render only users with a non-empty, non-null name?*ngFor does not support filtering directly. We use *ngIf inside the loop to conditionally show elements.*ngIf="user.name" filters out empty strings and null values because they are falsy in Angular templates.*ngFor="let user of users" <div *ngIf="user.name">{{ user.name }}</div> correctly uses *ngIf="user.name" inside the loop. *ngFor="let user of users" <ng-container *ngIf="user.name">{{ user.name }}</ng-container> has invalid syntax mixing *ngFor and *ngIf on the same element. *ngFor="let user of users | filter: user.name" uses a non-existent filter pipe. *ngFor="let user of users" <div *ngIf="user.name !== ''">{{ user.name }}</div> misses filtering null values.Pass the test and this pattern moves unknown