简体   繁体   中英

use a local component variable in another component without using selector

I have a component in angular named first_component . I'm using another component named second_component in its HTML like:

<second_component [addChildMode]='addChildMode' [defaultValues]='defaultValues' [chosenRelationIsInitialRelation]='chosenRelationIsInitialRelation'></second_component>

As you see, I'm passing some values from first_component to second_component such as addChildMode , defaultValues etc. using @Input() . (Since I'm using second_component with selector, I can use @Input() ). Now I have a showValue which is a local variable in second_component and I want to be aware of its change, Since I'm not using first_component by its selector, how can I notice when showValue is changed in second component? Ps first_component and second_component are just siblings. (Not child and parent)

Since you need to react to changes in showValue across multiple components, it is not (shouldn't be) local anymore. If you use NgRX or similar state management, you can put showValue in a store. I recommend this only if that variable has a global bearing.

But since it sounds more like couple components working closely together in a more or less local setting, I recommend using a shared service which will hold the showValue 's value in a an observable to which these 2 components can push/subscribe.

My suggestion would be using ChangeDetectionStrategy, that too if not that necessary or if you do not have any other way.

Using state management would be good for a large project, but would make application heavy if used in smaller projects.

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