angular - 如何在提交时保存 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() 方法。
解决方案
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];
}
);
});
}
}
推荐阅读
- php - 除法后如何获得本金的倍数
- javascript - 填充包含语言的 ASP 下拉列表
- java - 如何优化具有许多约束的问题
- django - 与 Django 通用视图中的 pk 不同的 url 路径
- azure - Azure 功能在未启用时显示为启用匿名
- r - 如何在 R 中使用 disk.frame 计算唯一实体?
- node.js - 无效的模式配置:`...` 不是路径 `ref` 的有效类型
- ruby-on-rails - MongoId 没有更新模型数据,也没有显示任何错误
- laravel - 使用 laravel 模型创建方法 Model::create 时我可以获取插入 ID
- authentication - 了解和使用 Microsoft 标识