首页 > 解决方案 > 提交后如何禁用Angular反应表单中的按钮

问题描述

我正在使用角度反应形式,如何在单击/提交后禁用按钮并更改按钮标签?

标签: angularangular-reactive-forms

解决方案


Angular 没有在表单上提供“提交的表单”属性。最好的方法是在提交表单时更新一个布尔值(您在模板中使用)并在适当的时候重置它。

以下示例使用响应式表单并使用表单数据伪造 POST。

<form [formGroup]="myForm"
      (ngSubmit)="onSubmit()">
  ... form stuff ...
  <button type="submit"
          [disabled]="isSubmitting">
    {{isSubmitting ? 'Submitting...' : 'Submit'}}
  </button>
</form>
onSubmit(): void {
  // catch if the form has errors
  if (this.myForm.invalid) return;

  // if no errors, continue with the submit
  this.isSubmitting = true;

  this.http
    .post('www.example.com', this.myForm.value)
    .subscribe(
      success => { this.isSubmitting = false },
      error => { ... handle the error ... }
    );
}


推荐阅读