问题描述
我正在将Angular8与Reactive表单一起使用。最初,我将禁用“提交”按钮,直到整个表单中都填入有效数据为止。
<div>
<form>
...........
</for>
<button [disabled]="checkifSaveEnabled() || submitted"
(click)="createNewPlan()">Save</button>
</div>
在班级(TS)文件中:
checkifSaveEnabled() {
if (this.formCreateNewPlan.pristine || !this.formCreateNewPlan.valid) {
return true;
}
return false;
}
createNewPlan(): void {
this.submitted = true;
this.myservice.create(this.formCreateNewPlan.value).subscribe(result => {
if (result.success && result.data.planId > 0) {
...
}
}
- 最初,“提交”按钮将处于已禁用模式。
- 输入所有“表单”值后,“按钮”将启用。
- 提交表单后,将再次禁用按钮。
我想要的是-提交后,如果API出现错误(例如“重复记录”),则需要对表单值进行一些更正。进行更正后,我需要再次启用该按钮。该怎么做?
解决方法
尝试一下...
HTML
<form [formGroup]="formCreateNewPlan">
................
<button [disabled]="!this.formCreateNewPlan.valid && submitted"
(click)="createNewPlan()">Save</button>
</form>
TS
submitted = true;
createNewPlan(): void {
this.myservice.create(this.formCreateNewPlan.value).subscribe(result => {
if (result.success && result.data.planId > 0) {
...
this.submitted = false;
}
}
,
我通过在finalize()下添加表单订阅来解决此问题
createNewPlan(): void {
this.myservice.create(this.formCreateNewPlan.value)
.pipe(finalize(() => {
this.formCreateNewPlan.valueChanges.subscribe(v =>
{
if (v.name) {
this.submitted = false;
}
});
}))
.subscribe(result => {
if (result.success && result.data.planId > 0) {
...
this.submitted = false;
}
}
,
在.ts文件中创建属性public submitted = false
。这将检测表单提交状态。
创建一个getter方法get isFormValid(): boolean {}
。这将检测表单的有效状态。
public submitted = false;
get isFormValid(): boolean {
return this.formCreateNewPlan.valid && !this.submitted;
}
在API成功或出现错误响应后重置提交状态。
createNewPlan(): void {
this.submitted = true;
this.myservice.create(this.formCreateNewPlan.value).subscribe(result => {
if (result.success && result.data.planId > 0) {
...
}
this.submitted = false;
}
在按钮上添加isFormValid方法以启用或禁用它。
<button [disabled]="!isFormValid" (click)="createNewPlan()">Save</button>