【问题标题】:Disable button if input is invalid如果输入无效则禁用按钮
【发布时间】:2018-12-10 08:57:31
【问题描述】:

我有一个很长的表单,但我想禁用特定按钮(在模板上,我不想在组件上这样做)只有当特定字段为空或有一些验证错误时,这个是我的表单示例:

<form #myForm="ngForm">
  <div class="form-group">
    <label>Email</label>
    <input [(ngModel)]="email" #email="ngModel" name="my_email" type="text" class="form-control" required>
    <span *ngIf="email.errors?.required">
      This field is required
    </span>
  </div>
  <button [disabled]="myForm.email.errors?.required">Some action</button> 
</form>

我不需要完整的有效表单来禁用该按钮,我只想根据该特定输入的值进行检查。

我该怎么做?我错过了什么?

【问题讨论】:

  • [disabled]="myForm.get('email').errors?.required"。对于语法问题,请考虑阅读the documentation
  • @tricheriche 已经尝试过了,并得到以下错误 => ERROR TypeError: jit_nodeValue_4(...).get is not a function
  • 为什么不在 disabled 属性上使用email.errors?.required

标签: angular forms validation angular2-template


【解决方案1】:

1 - 将模板变量 #email 重命名为 #emailInput 或任何不同于模型属性名称“email”的名称..

<input [(ngModel)]="email" #emailInput="ngModel" name="my_email" type="text" class="form-control" required>

2 - 在按钮的 disabled 属性和显示错误的 span 中使用模板变量#emailInpunt。

<button [disabled]="emailInput.errors?.required">Some action</button>

 <span *ngIf="emailInput.errors?.required">
    This field is required
 </span>

完整代码:

<form #myForm="ngForm">
  <div class="form-group">
    <label>Email</label>
    <input [(ngModel)]="email" #emailInput="ngModel" name="my_email" type="text" class="form-control" required>
    <span *ngIf="emailInput.errors?.required">
      This field is required
    </span>
    <button [disabled]="emailInput.errors?.required">Some action</button> 
  </div>
</form>

Stackblitz上试试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多