简体   繁体   中英

Sharing data between two sets of sibling components in Angular 5

Pretty new to Angular. Came from mobile app development.

I know there are so much information teaching how to share data between sibling components. But my question is sharing data between 2 sets of sibling components.

So code-wise, I have 2 components (A and B). When a button in A is clicked, B is updated. But UI-wise, there are 2 sets of this AB components. So when a button in A1 is clicked, B1 is updated. When a button in A2 is clicked, B2 is updated.

How can I achieve this?

What I have tried

In the first place, I used a service to share data. But then found that when A1 was clicked, both B1 and B2 were updated, which is what I don't want. Same for A2 was clicked.

Using a service to share data between two sibling components is definitely the best way of doing it, the only thing you need to do here is add a key to your components.

<comp-a [key]="1"></comp-a>
<comp-b [key]="1"></comp-b>
<comp-a [key]="2"></comp-a>
<comp-b [key]="2"></comp-b>

If the components are generated via a *ngFor , you could use the index of the loop or perhaps an object id if one is getting bound.

Anyway, when comp-a calls the service, you should include the key. When the event that comp-b is listening to gets fired, you should include the key in the event and comp-b should only respond to it if it matches its own key.

I think you provided your service at module level and that's why you have single instance.

Provide your service at component level. Create a wrapper component which holds Both A and B and provide the service at this component level. Each time the wrapper component is created a new instance of service will be created and that instance will be available only to A and B.

@Component({
    selector: 'app-abwrapper',
    templateUrl: './abwrapper.component.html',
    styleUrls: ['./abwrapper.component.scss'],
    providers: [{
        MyServiceToShareData
    }]
})

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