【问题标题】:On an Angular form how to disable submit button when a formControl.status === 'DISABLED'在 Angular 表单上,当 formControl.status === 'DISABLED' 时如何禁用提交按钮
【发布时间】:2021-11-10 20:50:34
【问题描述】:

当满足这两个条件时,我需要禁用提交按钮(Accept Button):

  1. form.valid !== true 或相同的 !form.valid
  2. formControl ProductType 状态未禁用
    this.form.controls.productType.status !== 'DISABLED'
    

ProductType 是必需的 formControl,因此它必须具有 form.valid 的值才能为真。当 productType formControl 在更改其祖父 formControl 的值时被暂时禁用时,就会出现问题。我需要这种行为来强制用户按以下顺序填写字段:Category > Family > ProductType

此时,虽然 ProductType formControl 是必需的,但由于它的状态是 DISABLED,所以它不计算在内,并且条件 form.valid 为 true。无论如何,当 productType formControl 被禁用时,我需要禁用提交按钮。我试过了,但它不起作用:

<button type="button" 
        [disabled]="!form.valid && form.controls.productType.status !== 'DISABLED'" 
        (click)="submit()">
</button>

有什么想法吗?

【问题讨论】:

  • 禁用的字段不会在表单中提交,因此通常不会被验证。我建议在模型上使用单独的属性来控制该验证。
  • @HereticMonkey 你能举个例子吗?我不明白你的意思
  • 只是控制器上的一个属性,如productTypeDisabled: boolean;。您可以根据需要将其设置为 true 或 false。在 ProductType 控件上,绑定 [disabled]="productTypeDisabled" 并在按钮上绑定 [disabled]="!form.valid &amp;&amp; productTypeDisabled"

标签: angular


【解决方案1】:

每个表单控件都有一个 disabled 属性,您可以检查它是真是假。

所以试试这个:

<button type="button" 
        [disabled]="!form.valid && !form.controls.productType.disabled" 
        (click)="submit()">
</button>

有关更多信息,您可以访问此处: https://angular.io/api/forms/FormControl

【讨论】:

  • 这段代码正是我尝试过的,但没有
猜你喜欢
  • 1970-01-01
  • 2018-07-10
  • 1970-01-01
  • 2016-04-03
  • 2019-09-20
  • 1970-01-01
  • 2010-09-11
  • 2018-06-30
相关资源
最近更新 更多