Angular-如何动态输出验证

时间:2017-09-10 06:04:55

标签: javascript angular

我想访问ng-touching和ng-valid类来打印错误信息,但无法弄清楚如何操作。这是我的代码 -

 <form #individual="ngForm">
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name" ngModel name="name" pattern="[a-zA-Z ]*" required placeholder="Enter Your Name">
      <label *ngIf="!individual.control.name.valid">INVALID</label>
    </div>
    <button type="submit" class="btn" (click)="onSave(individual)" [disabled]="!individual.valid">SUBMIT</button>
 </form>

1 个答案:

答案 0 :(得分:1)

在输入上添加一个本地变量,用于监视模型更改,然后您可以检查它的有效性:

<input type="text"  #myModel="ngModel"  class="form-control" id="name" ngModel name="name" pattern="[a-zA-Z ]*" required placeholder="Enter Your Name">
<label *ngIf="myModel.invalid">INVALID</label>

<label *ngIf="!myModel.valid">INVALID</label>

<强> DEMO