当Angular5中的字段为空时禁用该按钮[无效格式]

时间:2018-05-20 07:34:29

标签: angular angular-validation

我正在学习Angular5,对此不熟悉。

我有两个输入字段,一个按钮。处理完这两个字段的验证后,一旦输入两个字段,将启用该按钮。当表单无效时,我已禁用该按钮。但它没有用。

<form class="customerRegisteration-form">  
  <div class="form-row">
  <div class="form-group col-md-6">
    <label for="firstName">First Name</label>
      <input required ngModel name="firstName" id="firstName" class="form-control"  placeholder="First Name" #firstName="ngModel"/>
      <div class="alert alert-danger" *ngIf="firstName.touched && !firstName.valid">First Name is required</div>
  </div>
  <div class="form-group col-md-6">
    <label for="lastName">Last Name</label>
    <input required ngModel name="lastName" id="lastName" class="form-control" placeholder="Last Name" #lastName="ngModel"/>
    <div class="alert alert-danger" *ngIf="lastName.touched && !lastName.valid">Last Name is required</div>    
  </div>
  </div>
  <div class="form-group col-md-4">
      <button type="submit" class="btn btn-lg btn-block btn-info" [disabled]="!customerRegisteration.valid">
        <i class="fa fa-floppy-o"></i> Submit</button>
    </div>
</form>

如果有什么不对,请帮助我。

先谢谢。

2 个答案:

答案 0 :(得分:1)

您的表格应该有一个formGroup

<form  [formGroup]="customerRegisteration">

 <form class="customerRegisteration-form" #customerRegisteration="ngForm">

然后,

<button type="submit" class="btn btn-lg btn-block btn-info" [disabled]="!customerRegisteration.valid">

答案 1 :(得分:1)

您只需在标记中添加#customerRegisteration="ngForm",如下所示

<form class="customerRegisteration-form" #customerRegisteration="ngForm">  

完整代码

<form class="customerRegisteration-form" #customerRegisteration="ngForm">  
  <div class="form-row">
  <div class="form-group col-md-6">
    <label for="firstName">First Name</label>
      <input required ngModel name="firstName" id="firstName" class="form-control"  placeholder="First Name" #firstName="ngModel"/>
      <div class="alert alert-danger" *ngIf="firstName.touched && !firstName.valid">First Name is required</div>
  </div>
  <div class="form-group col-md-6">
    <label for="lastName">Last Name</label>
    <input required ngModel name="lastName" id="lastName" class="form-control" placeholder="Last Name" #lastName="ngModel"/>
    <div class="alert alert-danger" *ngIf="lastName.touched && !lastName.valid">Last Name is required</div>    
  </div>
  </div>
  <div class="form-group col-md-4">
      <button type="submit" class="btn btn-lg btn-block btn-info" [disabled]="!customerRegisteration.valid">
        <i class="fa fa-floppy-o"></i> Submit</button>
    </div>
</form>

请注意。我建议你阅读Angular Forms Article以及关于角形式的许多问题