Faster NativeScript ListView with Multiple Item Templates

Alexander Vakrilov
Dec 20, 2016 · 4 min read

Background

Virtualization (left) and Recycling(right)

Rendering Different Items

Using Single Template

<ListView [items]="items">
<ng-template let-item="item">
<StackLayout>
<GridLayout *ngIf="item.type === 'big'">
<!-- big item template -->
</GridLayout>
<GridLayout *ngIf="item.type === 'small' && item.imageUrl">
<!-- small item with image -->
</GridLayout>
<GridLayout *ngIf="item.type === 'small' && !item.imageUrl">
<!-- small item with no image -->
</GridLayout>
</StackLayout>
</ng-template>
</ListView>

The Better Approach

<ListView [items]="items" [itemTemplateSelector]="templateSelector">
<ng-template nsTemplateKey="big" let-item="item">
<!-- big item template -->
</ng-template>
<ng-template nsTemplateKey="small" let-item="item">
<!-- small item with image -->
</ng-template>
<ng-template nsTemplateKey="small-no-image" let-item="item">
<!-- small item with no image -->
</ng-template>
</ListView>
public templateSelector(item: NewsItem, index: number, items: NewsItem[]) {
if (item.type === "big") {
return "big"
}

if (item.type === "small" && item.imageUrl) {
return "small";
}
if (item.type === "small" && item.imageUrl) {
return "small-no-image";
}

throw new Error("Unrecognized template!")
}

Conclusion

Alexander Vakrilov

Written by

NativeScript core member. Co-organizer of Angular Sofia. Father of a (future) rockstar.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade