angular - 角度反应形式在保存后删除 formArray 元素
问题描述
在 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();
});
推荐阅读
- c# - 不使用 Task.Run() 安排工作时如何处理并发?
- github - 在 Github Action 中通过 Yarn 从 Github 包注册表下载私有模块?发布工作,但安装遇到“401 Unauthorized”
- symfony - 弃用:不建议使用 Doctrine\ORM\Mapping\UnderscoreNamingStrategy 而不使其知道数字
- sql-server - 为什么更新触发器没有触发?
- r - 如何在 R 中插入网格空间对象
- ios - 使用搜索字符串解析本地 JSON 文件
- javascript -
如何在 react/javascript中处理换行并将其转换为 html - rotation - ChartJS - x 轴标签方向
- python - DEAP:创造具有特定价值观的个体
- swift - 巨大的 Dictionary 对象时编译错误。打破表达