Dex
Dex

Reputation: 373

Accessing template variable className properties in angular 2

I have the following form with name input field. I am trying to put validations on the field. When I print the name.className value it prints ng-valid, ng-pristine and other classes.

I want to use *ngIf to display the error message but it is not working.

I tried *ngIf="name.ng-invalid" also but it is not working. Can anyone suggest what is wrong here?

    <form class="form-horizontal div-table" >
       <!-- Name -->
       <div class="form-group row-even">
          <label class="col-md-4 control-label">Name:</label>  
          <div class="col-md-7">
             <input id="name" name="name" type="text" class="form-control" [(ngModel)]="data.name" required minlength="3" maxlength="64" #name>
             <small *ngIf="name.ng-invalid">
             Name is required (minimum 3 characters).
             </small>
             <small>
             Element {{ name.className }}
             </small>
          </div>
       </div>
    </form>

Upvotes: 0

Views: 744

Answers (2)

Carl West
Carl West

Reputation: 53

Try setting #name="ngModel" on the input.

Then remove "ng" from

<small *ngIf="name.ng-invalid"> 

like so

<small *ngIf="name.invalid">

Upvotes: 1

Maks K
Maks K

Reputation: 3914

Try this code

<form (ngSubmit)="onSubmit()" #myForm="ngForm">
...
    <div [hidden]="name.valid || name.pristine"
         class="alert alert-danger">
         Name is required
    </div>

 ...   
    </form> 

Upvotes: 0

Related Questions