简体   繁体   English

Angular2在两个子组件之间传递数据

[英]Angular2 passing data between two child components

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. 我想在第一个孩子中插入表单数据,并在提交表单时路由到的另一个孩子中使用它。

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. 我怀疑我需要使用@input或@output但是在使用路由器插座时我找不到任何关于如何操作的文档。

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. 我目前的另一个解决方案是在第一个孩子中提交表单并在第二个孩子中调用表单时将数据保存在localstorage中。 Doesn't seem ideal. 看起来不太理想。

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. 如果您创建服务并在子A中设置数据,则可以从子B中检索它。唯一的问题是您需要将您创建的服务设置为父类的提供者,而不是子组件。

Here is an example of this Angular 2 passing object via route params possible? 以下是通过路径参数传递Angular 2传递对象的示例

You could use @ngrx/store to store data, then inject those into your route components. 您可以使用@ ngrx / store来存储数据,然后将这些数据注入到路径组件中。 See the examples there for implementation. 请参阅那里的示例以进行实施。

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

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