Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Using Array ...spread to enforce Pipe immutability.


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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...