Eric R
Eric R

Reputation: 713

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?

Upvotes: 4

Views: 595

Answers (2)

Deepak Anuraag
Deepak Anuraag

Reputation: 61

  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

Upvotes: 0

Vega
Vega

Reputation: 28701

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.

Upvotes: 4

Related Questions