如何将表单组数据传递到另一个组件中的Submit按钮(Angular 7)

问题描述 投票:0回答:1

我在将表单组数据传递到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'));
  }
}
javascript angular typescript angular-material angular7
1个回答
0
投票

首先要从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解释了反应形式如何工作以及如何使用它们。

美好的一天!

© www.soinside.com 2019 - 2024. All rights reserved.