1

This thing is the source of a truly nasty bug I found in my code.

So I have a child-component:

chilidComponent {
    @Input("current-value") currentValue: Array<{id: string, name: string}>
}

and the parent component uses child component like this

<child-component [current-value]="parentList"></child-component>

now if child component does something like

this.currentValue.push({id: "someId", name: "someName"})

the parent component have its "parentsList" modified even if there isn't an explicit two-way binding.

I know that objects (like an Array) are passed by reference, BUT is this a legit/wanted way for Angular to handle the component input?

What is the best practice for passing objects as inputs? How can I pass and object to a component that I don't want it to get modified even if it does inside the component?

Working with clones (inside or outside the child-component) sounds to me like a workaround you have to be aware of everytime component inputs are objects.

Should I start looking into Facebook's Immutable.js ?

RayX
  • 141
  • 1
  • 4
  • If the parent shouldn't see the new value, the child should copy the array. Otherwise, the child should notify the parent of the new value and then the parent should modify the array. – Frank Modica Nov 05 '18 at 20:41

1 Answers1

0

Arrays and Objects are references in JS. So even if you pass down the Array or Object down to a child component and assign it to a local variable, it will still point to the same reference Object. So, updating it will update the reference in the parent component.

Clone Object without reference javascript

Essentially, if you don't want to reference an object you can do this

var duplicateObject = JSON.parse(JSON.stringify( originalObject ));

For array

var newArray = oldArray.slice();
zer0
  • 4,657
  • 7
  • 28
  • 49
  • Thank you for your answare. The point is that somehow (for some kind of magic) I thought Angular would "protect" data passing as @Input. Btw I have found a solution based on cloning data (for it's a workaround), but looking better at this part of my code I made wrong design choices and I'm going to rethink it – RayX Nov 05 '18 at 21:19