Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 986 of the free egghead.io lessons, plus get Angular 2 content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Using Array ...spread to enforce Pipe immutability.

1:54 Angular 2 lesson by

Pipes need a new reference or else they will not update their output. In this lesson you will use the Array ...spread operator to create new Array to update pipe output without mutation.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

Pipes need a new reference or else they will not update their output. In this lesson you will use the Array ...spread operator to create new Array to update pipe output without mutation.

Avatar
kevin

Ugg this is more work and its incredibly difficult and it is different.

Avatar
John

There are libraries that make this much easier, but they aren't built into Angular 2 by default so I showed the "vanilla JavaScript way".

In reply to kevin
Avatar
SMP Web Team

sally forth? lol

In reply to egghead.io

Now without knowing it, we've kind of coded ourself into a corner, because if I try to add more items -- shave, or swim, or anything like that -- you can see I keep getting my TODO models. They're added, but they're not showing up in my list.

That's because a pipe expects a new reference to come into its transform method, or else it's not going to run at all. It's not going to check to see if any of the values inside of the array changed or if any items are added or removed to the array through something like push.

This is where immutability comes in, because instead of doing todos.push, which is essentially saying use this same array and add a new TODO model onto it, we're going to create a new method on our service called "add TODO" then jump into our TODO service. Say, "Add TODO," which takes in a TODO, which is a TODO model.

This time, instead of saying todos.push, we're going to say that TODOs is a new array, because we need our TODOs to point to something completely different. We'll use the spread operator, so this.todos, to essentially say, "Copy over the old TODOs and put them in this new array, and then add the new TODO to the end of that array."

When I save now I can add another TODO model like shave, swim, saunter, sally forth. Each time I add a new TODO model, because this reference is changing, it's not pointing to the same array, the search pipe filter knows to kick in and run the value.filter whenever that reference changes.

Now if you think this is more work, or it's incredibly difficult, or it's different, the main reason is because it gives you a huge performance boost by saving Angular from checking every single time an individual property or value changes on something that gets passed into a...

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?