angular 响应式表单在保存后删除 formArray 元素
angular reactive forms remove formArray elements after save
在angular 5 我有一个表格,用户可以添加多个费用记录,这些记录可以一次保存。保存后需要删除这些记录并返回到一行的初始状态。我已尝试按照以下代码进入初始状态,但在返回该状态时会触发验证。
ngOnInit() {
this.fastPostingForm = this.fb.group({
Charges: this.fb.array([
this.initCharge()
])
});
}
initCharge() {
return this.fb.group({
room: ['', Validators.required],
transactionCode: ['', Validators.required],
amount: ['', Validators.required],
quantity: [1, [Validators.required, Validators.min(1), Validators.max(9999)]],
window: ['', Validators.required],
reservationId: [''],
rsv:[{}]
});
}
addCharge() {
const control = <FormArray>this.fastPostingForm.controls['Charges'];
control.push(this.initCharge());
console.log(control.length);
}
saveForm(){
//save process
//clear form and remove form array elements
this.fastPostingForm = this.fb.group({
Charges: this.fb.array([
this.initCharge()
])
});
}
在 UI 中,使用以下条件对每个控件进行验证。
<mat-error *ngIf="!fastPostingForm.controls.Charges.controls[i].controls.room.valid && fastPostingForm.controls.Charges.controls[i].controls.room.touched">message
</mat-error
>
试试这个
saveForm(){
this.fastPostingForm = this.fb.group({
Charges: this.fb.array([
this.initCharge()
])
this.fastPostingForm.markAsUntouched();
this.fastPostingForm.markAsPristine();
this.fastPostingForm.updateValueAndValidity();
});
您无需重新创建群组。您可以简单地从 FormArray
中删除所有元素。使用 :
(<FormArray>this.fastPostingForm.controls.Charges).controls.splice(0, (<FormArray>this.fastPostingForm.controls.Charges).controls.length);
然后调用addCharge()
添加默认的第一个元素。
在angular 5 我有一个表格,用户可以添加多个费用记录,这些记录可以一次保存。保存后需要删除这些记录并返回到一行的初始状态。我已尝试按照以下代码进入初始状态,但在返回该状态时会触发验证。
ngOnInit() {
this.fastPostingForm = this.fb.group({
Charges: this.fb.array([
this.initCharge()
])
});
}
initCharge() {
return this.fb.group({
room: ['', Validators.required],
transactionCode: ['', Validators.required],
amount: ['', Validators.required],
quantity: [1, [Validators.required, Validators.min(1), Validators.max(9999)]],
window: ['', Validators.required],
reservationId: [''],
rsv:[{}]
});
}
addCharge() {
const control = <FormArray>this.fastPostingForm.controls['Charges'];
control.push(this.initCharge());
console.log(control.length);
}
saveForm(){
//save process
//clear form and remove form array elements
this.fastPostingForm = this.fb.group({
Charges: this.fb.array([
this.initCharge()
])
});
}
在 UI 中,使用以下条件对每个控件进行验证。
<mat-error *ngIf="!fastPostingForm.controls.Charges.controls[i].controls.room.valid && fastPostingForm.controls.Charges.controls[i].controls.room.touched">message
</mat-error
>
试试这个
saveForm(){
this.fastPostingForm = this.fb.group({
Charges: this.fb.array([
this.initCharge()
])
this.fastPostingForm.markAsUntouched();
this.fastPostingForm.markAsPristine();
this.fastPostingForm.updateValueAndValidity();
});
您无需重新创建群组。您可以简单地从 FormArray
中删除所有元素。使用 :
(<FormArray>this.fastPostingForm.controls.Charges).controls.splice(0, (<FormArray>this.fastPostingForm.controls.Charges).controls.length);
然后调用addCharge()
添加默认的第一个元素。