⚠️ This lesson is retired and might contain outdated information.

Use Sliding Gestures to Reorder an Ionic 2 List

Mike Hartington
InstructorMike Hartington
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

Gesture driven lists are a great way to take a simple UI element and make it fun. We'll look at how we can make swipe-able list items to reveal additional functionality, as well as being able to drag and reorder list items.

[00:00] Let's modify our data to create an array of three people. We'll move over to our template, add an NgFor to our ion-item, and iterate over every person of people.

[00:16] We can start to add more functionality to our list by incorporating gestures. For our first bit of functionality, we'll modify our template and add the ion-item-sliding component and wrap it around our ion-item. Let's also move the NgFor from the ion-item to the ion-item-sliding component.

[00:45] Next, we'll add the ion-item-options component right next to our ion-item. Inside our options component, we can start to add a variety of buttons, and these can be wired up to perform any actions that we want.

[01:00] By default, if you swipe the item, the option will show up on the right side. This can be changed by setting the side property on the options component. It can either be aligned on the right or on the left, but defaults to the right if no side is added.

[01:16] We can even create two options, set them to different sides, and then the item can be swiped from the left and from the right.

[01:29] Another option we have is the ability to drag and reorder our list items. We'll start by going up to our ion-list and adding the dynamic property of reorder, and set it to a class property, we'll add later. We'll also add a button to our main nav bar to be able to toggle this value from inside of our class.

[01:51] We'll add our button and give it an attribute of ion-button, and then we'll attach a click handler to call toggleReorder. Inside of the button, we'll give it the text of edit.

[02:07] Over in home.ts, we can add the property shouldReorder, and then create our method that will toggle this value for us. Here, we'll just say this.shouldReorder should equal the opposite of what its current value is. Now we can toggle our list for reordering, and drag the elements around.

[02:35] One thing you'll notice is that if we drag an item around and release it, the item doesn't stay in its new position. This is because itemReorder allows you to customize how to handle this. Now there are multiple ways of doing this, all of which are documented, but a quick and easy way to apply the change is to bind to the ionItemReorder event.

[02:54] We'll call $event.applyTo and pass in the original array of people. Now, we can drag the items around and have their positions update.