Angular2 在两个子组件之间传递数据 [英] Angular2 passing data between two child components

查看:49
本文介绍了Angular2 在两个子组件之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个子组件的组件.我展示了一个或另一个使用带有路由器插座的路由器.

I have a component with two childcomponents. I show one or the other with using the router with the router-outlet.

我想获取插入到第一个孩子中的表单数据,并在提交表单时路由到的另一个孩子中使用它.

I want to take form data inserted in the first child, and use it in the other child which I route to upon submitting the form.

我怀疑我需要使用@input 或@output,但我找不到有关使用路由器插座时如何执行此操作的任何文档.

I suspect I need to use @input or @output but I can't find any documentation on how to do it when using the router-outlet.

我目前的其他解决方案是在第一个孩子提交表单并在第二个孩子中调用它时将数据保存在localstorage中.看起来不太理想.

My current other solution is to save the data in the localstorage when submitting the form in the first child and calling it in the second child. Doesn't seem ideal.

推荐答案

您可以通过服务传递数据.如果您创建一个服务,并在子 A 中设置数据,那么您可以从子 B 检索它.唯一的问题是您需要将您创建的此服务设置为父类的提供者,而不是子组件的提供者.

You could pass the data via a service. If you create a service, and set the data in child A, you could then retrieve it from child B. The only catch is you need to set this service you create as a provider for the parent class, and not for the child components.

以下是此 Angular 2 通过路由参数传递对象的示例可能吗?

这篇关于Angular2 在两个子组件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆