简体   繁体   中英

Parent and Child communication in Angular

I have two questions:

  1. If we send any variable from parent to child and than any changes (let's say value change) in Child component. This changes will automatically reflects in Parent component or not? if not how can I reflect back?

  2. I have a demo for this in which Parent comp is sending an array to child as (child has add/edit functionality). Whenever I am adding or updating any element changes is being reflected in parent comp as well (I am displaying listing in parent template).

So initially I thought that I don't need to care about sending changes back to parent as it's already working.

However, for update I have used 2 variables editForm and edit_id which is also sent by parent to child on update when I am setting editForm = false and edit_id = 0. Changes not reflected in Parent only child variables changed.

So both are confusing me now.

What might be wrong here? Below is the link where you can find my code:

https://stackblitz.com/edit/angular-rw74sc

Angular has nothing to do with this is something related to Is JavaScript a pass-by-reference or pass-by-value language?

So in java script when you copy primitive types (number, string, etc.) value will be copied not the reference itself, but in case of objects reference will be copied and change will reflect to parent object as well.

Below is interesting example for both reference type and value type

 var obj={a:10}; var copyObj=obj; obj.a=12; console.log(obj.a);//example of reference type you can see the output will be 12; var a=10; var b=a; b=12; console.log(a);//example of value type here output is still 10

One more related SO here

There are many ways to communicate from child to parent for example you can use @Output , shared service , subject , eventemitter etc

Here is an SO ans related to child parent communication

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM