简体   繁体   English

在Angular中的兄弟组件之间传递数据

[英]Passing Data between sibling components in Angular

在此输入图像描述 Above image depicts my Angular 2 application , Main component has two child components "FromComponent" and "ToComponent". 上图描绘了我的Angular 2应用程序,Main组件有两个子组件“FromComponent”和“ToComponent”。

"FromComponent" displays a list of items with a checkbox beside each item. “FromComponent”显示项目列表,每个项目旁边都有一个复选框。

When user selects/deselects an item in FromComponent , it should be added/removed from ToComponent list of items. 当用户选择/取消选择FromComponent中的项目时,应该从ToComponent项目列表中添加/删除它。

what is the best way to implement this in angular 2 ? 在角度2中实现这个的最佳方法是什么?

You would want to use a shared service that stores this information. 您可能希望使用存储此信息的共享服务。 Using observables as the storage mechanism would allow the To Component to subscribe to that subject and watch for any changes that the From component makes to that observable. 使用observable作为存储机制将允许To Component订阅该主题并监视From组件对该observable所做的任何更改。

Check out more information on Subject and BehaviorSubject types in rxjs. 查看有关rxjs中Subject和BehaviorSubject类型的更多信息。

I have implemented that using a service as described here where parent-child communication is described. 我已经使用这里描述的服务实现了这一点 ,其中描述父子通信。 A service can connect a parent with all its children. 服务可以将父级与其所有子级连接起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM