Reputation: 501
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
Upvotes: 4
Views: 17249
Reputation: 440
<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
Upvotes: 2
Reputation: 657741
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)
Upvotes: 1
Reputation: 58981
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">
Upvotes: 1