【问题标题】:How to Pass Form Group Data to Submit Button in Another Component (Angular 7)如何将表单组数据传递给另一个组件中的提交按钮(Angular 7)
【发布时间】:2020-08-27 10:45:48
【问题描述】:

我在将表单组数据传递给 saveDialog() 函数时遇到问题,该函数会更新提交按钮上的表单数据。

我将如何在 Angular 7 中做到这一点?我正在尝试将每个表单组的所有组件分开,并使用一个按钮一起提交/更新?

modify-view-action.component.html

      <form [formGroup]="modifyActionForm" (ngSubmit)="saveDialog()">
    <div class="container" fxLayout="row" fxLayoutGap="25px">
      <div class="column1" fxLayout="column">
        <mat-form-field>
          <mat-label>Name</mat-label>
          <input matInput>
          <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
        </mat-form-field>
        <mat-form-field>
          <mat-label>Keyword</mat-label>
          <input matInput>
          <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
        </mat-form-field>
        <mat-form-field>
          <mat-label>Description</mat-label>
          <input matInput>
          <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
        </mat-form-field>
        <mat-form-field>
          <mat-label>Icon</mat-label>
          <input matInput>
          <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
        </mat-form-field>
        <mat-form-field>
          <mat-label>Priority</mat-label>
          <input matInput>
          <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
        </mat-form-field>
      </div>
    </form>

modify-view-action.component.ts

export class ModifyViewActionComponent implements OnInit {
  modifyActionForm: FormGroup;
  dbrAction: any;


  constructor() { }

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.dbrAction = JSON.parse(localStorage.getItem('DbrAction'));
  }
}

【问题讨论】:

  • 试试这个therichpost.com/…
  • FormGroup 数据在哪里? modifyActionForm 初始化在哪里?
  • 请创建一个 stackblitz 来重现相同的内容

标签: javascript angular typescript angular-material angular7


【解决方案1】:

首先,为了从 FormGroup 中获取数据,您需要在每个要从中获取数据的输入中添加 formControlName。像这样:

 <mat-form-field>
      <mat-label>Name</mat-label>
      <input matInput formControlName="name">
      <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
 </mat-form-field>

您还需要在 .ts 文件中声明每个控制器的 FormGroup。像这样:

modifyActionForm = new FormGroup({
  name : new FormControl(),
  keyword: new FormControl(),
  description: new FormControl(),
  // And that ⬆ for each input in your form
})

要从此 FormGroup 中获取数据,您需要这样做:

this.modifyActionForm.value

您将获得一个包含输入数据的对象。

您的问题不是很清楚,但是如果您想将数据(例如 FormGroup)从一个组件传递到另一个组件,则存在许多技术。

我建议您阅读 Jeff Delaney 的这篇精彩文章,其中解释了在 Angular 组件 (Fireship.io - Sharing Data between Angular Components) 之间共享数据的不同方式,而这篇 Fireship.io - Angular Reactive Forms Basics Guide 解释了响应式表单的工作原理以及如何使用使用它们。

美好的一天!

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2020-03-28
    • 2017-01-31
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多