1

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

RS Roshi
  • 53
  • 1
  • 6

1 Answers1

4

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.

Will Alexander
  • 3,425
  • 1
  • 10
  • 17
  • So, you're saying change detection won't work for value types? – RS Roshi Jan 05 '22 at 16:43
  • No, I'm saying that the value you modify in a sibling is a value, not a reference to the variable in the parent. That means you can't change a value received by a child and expect the parent's value to change as well. Even if you COULD do that (as you technically can with reference types), it would be terrible code smell. Angular best practice is to use either a service or an @Output. (You could technically also use Redux Actions, if using something like NgRx or Ngxs). – Will Alexander Jan 05 '22 at 16:46
  • Alright, I have also witnessed a strange behavior where for value-types it does detect changes for the first time. But no detection after that. Thoughts? – RS Roshi Jan 05 '22 at 16:50
  • 1
    Sounds like more incorrect architecture. You won't have any of those problems if you follow Angular best practices :-) – Will Alexander Jan 05 '22 at 16:54