简体   繁体   中英

How to send data to nested component (parent-child(parent)-child)?

I have three components (C1, C2, C3)nested, which means C2 is invoked in C1 and C3 is invoked in C2. I wanted to send the data which is in C1 to C3 via property binding.

In C1's template, I did bind the variable, which I can receive in C2 via @Input and in C2's template, I did bind the same variable (@Input) but I am not getting in C3.

It only works if I store the data in a temporary variable in C2 and bind the (temporary) variable in C2's template, can receive in C3.

So is it mandatory to store the data in a temporary variable or is there any workaround?

Your nested C3 component should also be updated when C1 is updated.

Out of curiosity, I have created a simple stackblitz to try this out: https://stackblitz.com/edit/angular-i18qg3

  • C2 component is nested in app (root) component. rootProperty is binded to C2Property.
  • C3 component is nested in C2 component. C2Property is binded to C3Property.

When "Update Variable" button is clicked, it updates rootVariable, which is binded to C2 and subsequently C3.

Do check if you have changed your change detection to onPush in C2 or C3.

Taken from: https://blog.angular-university.io/onpush-change-detection-how-it-works/#onpushchangedetectionanddirectobjectmutability

This situation occurs because:

  • we mutated the user object directly
  • but OnPush works by comparing references of the inputs of the component
  • because we did not provide a reference to a new object but instead mutated an existing one, the OnPush change detector did not get triggered

If we would change the implementation of changeUserName() to create a new user instance instead of mutating the existing instance , everything would work as expected

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