Need to take a subset of elements within an array in your Angular app?

That's typically easy enough. In the component class.

But what if you need to do that same thing within the template?

Well, the good news is that you can do it there, too.

And in this guide, I'll show you how to make it happen.

With SlicePipe

Of cousre, the title gives away the game here, doesn't it? You need to do this with SlicePipe.

But what is SlicePipe?

You will be shocked to learn it's a pipe. Specifically, it's a pipe that creates a subset of elements from a larger array.

By the way: you won't use the class name (SlicePipe) in the template code. Instead, you'll use the pipe name: slice.

So let's get slicing.

How It Works

If you looked at the link above, you'll see that SlicePipe accepts two (2) input parameters:

  • The start index
  • The end index

Only the first is required. But if you leave the second one out, it defaults to undefined.

I wouldn't recommend going that route so I think you should use both parameters.

Now let me show you how to do it.

So let's say you're working on a CRM application. The current component keeps an array of all contacts associated with the current users.

Let's further assume that you want to display just the first five contacts on the screen. But you need to do it using template markup and not with any special code in the component class.

In that case, you'd opt for a solution that looks like this:

<div *ngFor="let contact of contacts | slice:0:5">
  {{ contact.firstName}} {{contact.lastName}}
</div>

That slice you see in the *ngFor directive makes use of the SlicePipe class you saw earlier. The two numbers, separated by colons, represent the starting and ending indexes.

In this case, the starting index is 0 (the first element in the array) and the ending index is 5 (the sixth element in the array because it's using 0-based indexing). 

But... as is the case with other programming languages, the last element doesn't get included in the slice. So the output won't include the sixth contact.

Don't blame me. I just work here.

If you've got an array of 12 contacts in contacts, the output above will display the first and last names of the first five.

But there's another way to accomplish the same thing.

Another Way

You could also go this route:

<div *ngFor="let contact of contacts.slice(0,5)">
  {{ contact.firstName}} {{contact.lastName}}
</div>

With that code, you're using the slice() method instead of SlicePipe

It works but it feels wrong. Seems like slice() belongs in the component class while the slice pipe belongs in the template.

But if you're in need of a hack, go with that.

Wrapping It Up

Now you're ready to handle slicing in your template code!

It's up to you to take what you've learned here and apply it your own business requirements.

Have fun!

Photo by Karolina Grabowska from Pexels