Ayush Singh
Ayush Singh

Reputation: 306

Angular- How to output Validation dynamically

I want to access classes ng-touched and ng-valid to print error message but couldn't figure out how to. Here's my code-

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

Upvotes: 2

Views: 227

Answers (1)

Vega
Vega

Reputation: 28738

Add a local variabale on the input which will watch for the model changes, then you can check it's validity:

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

or

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

DEMO

Upvotes: 1

Related Questions