在 Angular 6 中将多个组件的数据收集到一个的最佳方式 [英] The best way to collect data from multiple components into one in Angular 6

查看:17
本文介绍了在 Angular 6 中将多个组件的数据收集到一个的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Angular 比较陌生,我知道我的问题可能非常原始,但请就我的情况提供最佳解决方案.

I am relatively new to Angular, and I understand my question might be very primitive, but please advice me the best solution in my case.

我有一个步进器(来自 Angular Material);每个步骤的内容在不同的组件中;在所有步骤中,我们都使用多个输入字段从客户那里收集数据.

I have a Stepper (from Angular Material); the contents of each step are inside different components; in all the steps we collect data from a customer using multiple input fields.

代码如下所示.

步进器:

<mat-horizontal-stepper #stepper>
  <mat-step [stepControl]="stepOne">
    <ng-template matStepLabel><span class="someClass">Customer Information</span></ng-template>

    <step-one></-step-one>

  </mat-step>
  <mat-step [stepControl]="stepTwo">
    <ng-template matStepLabel><span class="someClass">Payment Information</span></ng-template>

    <step-two></step-two>

  </mat-step>
    ...
  <mat-step>
    <ng-template matStepLabel><span class="someClass">Confirmation</span></ng-template>

    <confirmation></confirmation>

  </mat-step>
</mat-horizontal-stepper>

内容(很多这样的字段):

Contents (lots of fields like this):

  <mat-form-field class="dcp-input-field">
    <input matInput placeholder="First Name" formControlName="name" [errorStateMatcher]="matcher">
      ...
  </mat-form-field>

我想要的,是收集最后一个确认"控制器中的所有数据,展示给客户.我知道组件之间有多种通信方式,但在这种情况下哪种方式最好?我试过使用服务,但出了点问题.

What I want, is to collect all the data in the last "confirmation" controller, to show it to the customer. I know there are various ways of communication between components, but which one is the best in this case? I've tried using service, but something went wrong.

请给我一个可以回答我问题的参考文献的链接,应该足够了.

Please just send me a link to any reference that can answer my question, it should be enough.

感谢您的建议.

推荐答案

在您的情况下,服务不是正确的解决方案.

A service is not the correct solution in your case.

您应该在父组件中拥有数据对象并将其作为 input 传递给所有子组件(步骤).

You should have the data object in parent component and pass it as an input to all child components (steps).

编辑:

示例代码:

父母:

在父组件中定义数据对象:

Define the data object in the parent Component:

data = {};

将数据对象传递给父模板中的第一步子组件:

Pass data object to step-one child component in parent template:

<mat-horizontal-stepper #stepper>
  <mat-step [stepControl]="stepOne">
    <ng-template matStepLabel><span class="someClass">Customer Information</span></ng-template>
    <step-one [data]="data"></-step-one>
  </mat-step>
  ...

儿童:

定义要从父级接收的@Input 数据对象:

Define the @Input data object to receive from parent:

@Input() data: {};


总结:这样,所有子组件都将使用父组件的数据对象,并且一旦在父组件中提交,数据就在那里.

Summary: This way, all children will work with the parent's data object, and once submitted in parent component, the data is there.

这篇关于在 Angular 6 中将多个组件的数据收集到一个的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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