首页 > 解决方案 > 如何在提交时保存 FormArray 字段的值?

问题描述

我有 5 个字段 MeetingId、TimeId、Date、Start、End,我希望 Date Start 和 End 作为 FormArray 字段。我有正确的添加和删除功能。请有人帮助我如何保存它。

我尝试过使用表单组。有效。但是表单数组不起作用


<form [formGroup]="scheduleForm" class="scheduleForm">
  <ol>
    <li formArrayName="scheduleFormArray"
        *ngFor="let item of scheduleForm.get('scheduleFormArray').controls; let i=index" [formGroupName]="i">
      <mat-form-field appearance="outline" class="dateField">
        <input matInput [matDatepicker]="picker1" [min]="minDate" placeholder="Datum" formControlName="date">
        <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
        <mat-datepicker #picker1></mat-datepicker>
      </mat-form-field>
      <mat-form-field appearance="outline" class="from">
        <input matInput placeholder="von" formControlName="start">
      </mat-form-field>
      <mat-form-field appearance="outline" class="to">
        <input matInput placeholder="bis" formControlName="end">
      </mat-form-field>
      <mat-icon class="cancel" (click)="deleteScheduleColumn(i)">delete</mat-icon>
    </li>
  </ol>
  <mat-icon (click)="addItems()" class="addInput">add_circle</mat-icon>
  <button mat-button class="next" (click)="saveSchedule()">Weiter</button>
</form>

private scheduleFormArray: FormArray;
private scheduleForm: FormGroup;
schedule: TimePeriod[] = [];
public newSchedule: TimePeriod = new TimePeriod(0, null, null, null, null);

public saveSchedule() {
    if (this.scheduleForm.invalid) {
      return;
    } else {
      this.newSchedule.tID = this.scheduleForm.value.tID;
      this.newSchedule.date = this.scheduleForm.value.date;
      this.newSchedule.start = this.scheduleForm.value.start;
      this.newSchedule.end = this.scheduleForm.value.end;
     this.newSchedule.mID = this.scheduleForm.value.mID;
      this.timePeriodService.addSchedule(this.newSchedule).subscribe(
        (t: TimePeriod) => {
          let newTimePeriod = this.schedule;
          newTimePeriod.push(t);
          this.schedule = [...newTimePeriod];
        }
      );
    }
  }

我的 addItems() 和 deleteScheduleColumn() 方法有效。请帮助我使用 saveSchedule() 方法。

标签: angularformarray

解决方案


Thank you all. I have made the below changes and it is now working.

public saveSchedule() {
     if (this.scheduleForm.invalid) {
      return;
    } else {
      this.scheduleFormArray.value.forEach(s => {
        this.newSchedule = new TimePeriod(s.tID, s.date, s.start, s.end, s.mID);
        this.timePeriodService.addSchedule(this.newSchedule).subscribe(
          (t: TimePeriod) => {
            let newTimePeriod = this.schedule;
            newTimePeriod.push(t);
            this.schedule = [...newTimePeriod];
          }
        );
      });
    }
  }

推荐阅读