如果输入无效,则禁用按钮

时间:2018-12-10 08:57:31

标签: angular forms validation angular2-template

我的表格很长,但是仅当特定字段为空或存在一些验证错误时,我才想禁用特定按钮(在模板上,我不想在组件上使用它)是我的表单示例:

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

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

我该怎么办?我想念什么?

1 个答案:

答案 0 :(得分:0)

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

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

2-在按钮的disable属性和显示错误的范围中使用模板变量#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

上尝试