【问题标题】:Re-Enable Submit button after doing some Corrections in an Angular Form在 Angular 表单中进行一些更正后重新启用提交按钮
【发布时间】:2020-10-19 10:44:46
【问题描述】:

我正在使用带有反应形式的 Angular8。最初,我禁用了提交按钮,直到整个表单都填充了有效数据。

<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 收到错误(比如“重复记录”),我需要在表单值中进行一些更正。进行更正后,我需要再次启用该按钮。如何做到这一点?

【问题讨论】:

    标签: angular angular-reactive-forms submit-button


    【解决方案1】:

    我通过在 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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个...

      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;
          }
       }
      

      【讨论】:

      • 但是这个,提交后,按钮不会被禁用。
      【解决方案3】:

      在您的 .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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 2021-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-07
        • 2016-03-02
        相关资源
        最近更新 更多