Display lists using NativeScript’s ListView component

    Nathan WalkerNathan Walker

    The NativeScript ListView component uses the native platform list controls under the hood for superior performance and native virtual scrolling (ListView widget on Android and UITableView on iOS).



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    00:00 To display a list, you may usually use an NG4 for that with Angular. NativeScript provides a powerful component for this called the 'ListView'. So instead of this stack layout, let's drop a ListView in here. It provides a lot of events that we can wire into. But for this example, we're just going to look at the itemTap event, and we're going to bind the items property to a property called 'items' on our component.

    00:26 And you can see that we get a template inside, and this is where we define the view for each row. And this creates a local variable item that is available to each template here, and we're going to bind to the title property of each item. So let's add each item here.

    00:43 And we'll just have four items. Let's add the on-itemTap event. And we'll just pass an argument of 'E' for 'event' here. We could import a type for this event. But sometimes, you don't know the type that gets passed in on an event, and in those cases, it's handy just to print out the properties on that event. And we'll just print out what the value is. Let's look at both on either platform.

    01:09 We'll see that they do look similar. What is interesting about iOS is that it has a max height by default, and so, we're going to want to adjust this. And if we tap on an item, we can see that we get all the keys that are off of that event that gets passed through -- it is the itemTap event. We actually get a reference back to the ListView object, and we can see this index comes through and it tells us exactly what index we tapped on. There we can see 'Index One'.

    01:35 So we can grab and use that property if we want to access that object. Let's first adjust our height so it's correct on iOS. For now, we'll just add an in-line height attribute. You can add this to the CSS class, if you like. And if we look at that now, it doesn't look so great on Android, but it looks really good on iOS. We can see we've got 100-percent ListView height.

    01:55 NativeScript provides a way to deal with scenarios like that. So in iOS, we can pretext this attribute with iOS:, and then for Android, we can use the Android prefix and say '75-percent'. And now, on Android, our list appears much better, and on iOS, we still have the full height.