In Angular 2, ngIF does not work when I try with two-way binding

I work with Angular2the concept of two-way binding [(ngModel)]. I have a form with my page, and I have to check the clean state of the element. Therefore, for verification, I used ngIfto check the pristine state of the element. But the condition does not work. I need to check the pristine state for each model change. Below is the page app.component.html:

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

+4
source share
3 answers

pristineis a property Controlnot << 22>.

,

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

( )

+1

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

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

+2

pristine is true if the user has not yet interacted with the form. Probably you want to check instead of dirty ? You can also use the tag hiddenand replace

<div *ngIf="employeeDob.pristine">

with:

<div [hidden]="employeeDob.pristine">
+1
source

Source: https://habr.com/ru/post/1649752/


All Articles