简体   繁体   中英

Angular - Share Data Between Sibling Components Without Sharing Between Instances

I'm writing a module that contains three separate components. These components work together, so it makes sense to use a Service to help keep track of everything.

|    
|- wrapper.component.ts
|
|- wrapper.service.ts
|
|- wrapper.module.ts
|
|- child-component1.component.ts
|
|- child-component2.component.ts

The problem is that, if you create two instances of the base component in the app, the Service shares the data between both instances of the component.

What's the proper way to share data between siblings without sharing it between all instances of the component?

Providing the service at the component level:

@Component({
    ....
    providers: [myService]
})

This way the service instance is shared between the component and its children, but not other instances of the component.

  1. You can emit an event using event emitter from child 1 component to parent
  2. change the input to child 2 from parent with data emitted from child 1
  3. Access the data in ngOnChange of child 2

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