angularangular-changedetectionngonchangesngzone

Angular @Input value not changing when changed from Parent Component


I have added same child component three times in a single parent component enter image description here

And below is the change function called on one of the children's components to change the selectedName in other two child components The @Input is type of string if I change it to object it work fine.

enter image description here

And this is how child component looks like enter image description here


Solution

  • Your issue seems to be one of value vs. reference types.

    The reason it works as an Object is that Objects are reference types: when you pass an Object to a component, you are passing its reference, not a "copy". That means that when you mutate that Object (in a child, for example), any component with a reference to that Object will "see" the change.

    The same isn't true for value types. When you pass a string, number, or boolean to a component, you are passing the value, completely unlinked from the source variable.

    You shouldn't be mutating something inside a child component which is relied upon by its siblings and/or parents. You should either be using a service (with methods for mutation) or an @Output to bubble the change event upwards from the child.