In angular 5 I have a form with user can add multiple records of charges which can save at once. after save need to remove those records and go back to initial state with one row. I have tried as following code it goes to initial state but the validation is firing when go back to that state.
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()
])
});
}
In the UI validation is done using following condition for each control.
<mat-error *ngIf="!fastPostingForm.controls.Charges.controls[i].controls.room.valid && fastPostingForm.controls.Charges.controls[i].controls.room.touched">message
</mat-error
>
this.fastPostingForm.reset();?