[英]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()
添加默認的第一個元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.