In Angular 2, ngIF is not working when i am trying with two way binding

15,154

Solution 1

pristine is a property of the Control not of the value.

You might want to use

<input #employeeDobCtrl="ngForm" type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" required  />        
<div *ngIf="employeeDobCtrl.pristine">    

(for the old forms module)

Solution 2

<input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" #date="ngModel" required />
<div [hidden]="date.valid || date.pristine"> <p>Please enter the date</p> </div>

straight outta documentation

https://angular.io/docs/ts/latest/guide/forms.html

Solution 3

pristine is true if the user has not interacted with the form yet. You probably want to check for dirty instead? You can also use the hidden tag and replace

<div *ngIf="employeeDob.pristine">

with:

<div [hidden]="employeeDob.pristine">
Share:
15,154
Sasi Dhivya
Author by

Sasi Dhivya

Updated on June 28, 2022

Comments

  • Sasi Dhivya
    Sasi Dhivya almost 2 years

    I am working with Angular2 with two way binding concept [(ngModel)].I have form with my page and I have to validate the pristine state of the element. So for validation I have used ngIf to check the pristine state of the element. But the condition is not working. I need to check the pristine state for every model change. Below is my app.component.html page:

     <form (ngSubmit)="angular2form(myAngular2Form.employeeDob)" [ngFormModel]="myAngular2Form">
    
     <input type="text" class="form-control" id="employee" name="employee" [(ngModel)]="employeeDob" required  />            
      <div *ngIf="employeeDob.pristine">
        <p>Please enter the date</p>
     </div>
     <button type="submit" class="btn btn-primary">Register</button>
    
    </form>
    

    This is my component:

     export class AppComponent {
    
    employeeDob: String;
    
      constructor(private myform: FormBuilder) {
        this.employeeDob = '';
     }
     angular2form(date) {
         alert("date submitted successfully");
     }
     }
    

    Thanks for any suggestion

  • Sasi Dhivya
    Sasi Dhivya almost 8 years
    EXCEPTION: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("" class="form-control" id="employeeDob" [(ngModel)]="employeeDob" name="employeeDob" [ERROR ->]#employeeDob="ngModel" required />
  • Kyrsberg
    Kyrsberg almost 8 years
    What version of angular are you using? I think that is fixed in newer version. github.com/angular/angular/issues/9363
  • Sasi Dhivya
    Sasi Dhivya almost 8 years
    I am using angular - common/core 2.0.0-rc.1"
  • Kyrsberg
    Kyrsberg almost 8 years
    Sadly I believe my answer works only for rc.3 and later versions