我有一个ngFor表,可以在其中以编辑模式添加一行,其中有一些选择框。
我能够编辑,取消数据并将其保存到mysql数据库中。
问题是,我需要在编辑模式下在表中动态添加一行以上,并将它们全部保存一次。实际上,这是我办公室的一个项目,因此我无法共享任何代码。但我正在使用
myArray.splice(0,0,newObject);
myArray = [...myArray]
在表中添加新行。如何使用具有单独取消按钮的同一行添加多行。
您可以使用FormArray
完成该操作。基本上,表格的每一行都是FormArray
:
<form [formGroup]="_form" novalidate>
<table>
<tbody formArrayName="data">
<tr *ngFor="let array of _form.get('data').controls; index as i"
[formGroupName]="i">
<td>
<input matInput
formControlName="name"
placeholder="Name"
required>
</td>
<td>
<input matInput
formControlName="surname"
placeholder="Surname"
required>
</td>
<td>
<select formControlName="gender">
<option [ngValue]="null">GENDER</option>
<option *ngFor="let g of _genders" [ngValue]="g">
{{g}}
</option>
</select>
</td>
<td>
<button (click)="_removeRow(i)" type="button">
Remove
</button>
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>
<button type="button" (click)="_addRow()">
New Row
</button>
</td>
</tr>
</tbody>
</table>
</form>
注意,表单数组中的控件也是FormGroup
,而不是简单控件。整体_form
可以声明为:
this._form = this._formBuilder.group({
data: this._formBuilder.array([])
});
您可以通过执行以下操作将FormGroup
添加到FormArray
:
const formArray: FormArray = this._form.get('data') as FormArray;
const form = this._fb.group({
name: ['', Validators.required],
surname: ['', Validators.required],
gender: [null, Validators.required]
});
formArray.push(form);
您可以通过从formArray删除行来删除行:
const formArray: FormArray = this._form.get('data') as FormArray;
formArray.removeAt(index);