Not getting the updated value of ngModel at custom validator in primeng p-calendar

124 Views Asked by At

I am trying to use an p-calendar with icon like this

                 <p-calendar 
                        [showOnFocus]="false"
                        [locale]="sw"
                        dateFormat="yy-mm-dd"
                        [style]="{'width': '120px'}"
                        [showIcon]="true"
                        [(ngModel)]="abc.efg.fromDate"
                        [check]="checkDate()"

                        [keepMessage]="true"
                        [keepInvalid]="true"
                        (onSelect)="dateOnSelect(abc.efg, $event)"
                        alwaysShow></p-calendar>

and the implementation of checkDate() in the app component looks like this

checkDate(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      console.log('date from : ', this.abc.efg.fromDate);
      // other implementation
              }
      }

The issue I am facing is that, whenever I pick a date (by clicking the icon), I get call in the checkDate() and the value of this.abc.efg.fromDate is always null, but I am getting the value of this.abc.efg.fromDate in the function dateOnSelect($event)

 setDateOnSelect(Type t, event): void {
    t.fromDate = event;
    console.log('new date from: ', this.abc.efg.fromDate);
  }

How can I solve this ?

EDIT: Is there anything that I can do at the validator other than directly passing the value to the function. ?

My guess : Angular's two-way binding with [(ngModel)] is asynchronous, and changes might not be reflected immediately in the validation function. Any idea to overcome this ?

PS: this.abc.efg.fromDate is a date field.

2

There are 2 best solutions below

10
Bhavy Ladani On

To fix this issue, you can use "ngModelChange". This directly captures the change and return the value.

<p-calendar 
  [showOnFocus]="false"
  [locale]="sw"
  dateFormat="yy-mm-dd"
  [style]="{'width': '120px'}"
  [showIcon]="true"
  [(ngModel)]="abc.efg.fromDate"
  [keepMessage]="true"
  [keepInvalid]="true"
  (onSelect)="dateOnSelect($event)"
  (ngModelChange)="checkDate($event)"
  alwaysShow>
</p-calendar>

Create a function in your ts file.

checkDate(newDate: any){
  console.log(newDate);
}

Hope this works and fix your issue.

0
JITHIN_PATHROSE On

The data was binding perfectly with

[ngModelOptions]="{updateOn: 'blur'}"

For some reason ngModelChange was not working for me.