How to prevent bsValueChange from firing on page load in angular?

Viewed 4949

I have been using ngx-bootstrap's datepicker to listen for an onchange event so that I could fetch data whenever the user changes the date from input.

Everything works fine except for the fact bsValueChange fires initially on page load which returns an Unhandled rejection SequelizeDatabaseError: invalid input syntax for type date: "Invalid Date".

Here is my datepicker code block

<input class="form-control" #drp="bsDaterangepicker" bsDaterangepicker [(ngModel)]="bsRangeValue" [bsConfig]="{ rangeInputFormat: 'MM/DD/YYYY' }"
  (bsValueChange)="onValueChange($event)">

I have looked into this github issue as well but this is not working for me either as ngModelChange doesn't work anymore.

I only want bsValueChange to fire once when the entire page has loaded.

4 Answers

use onHidden event instead of bsvalueChange

While page is loading, the onValueChange($event) method will be called. I found no way to prevent this instead you can try something like this. Have a number variable declared outside the method.

counter = 0;
OnChangeValue($event){
     this.counter = this.counter+1;
     if(this.counter>2 && event.length!=0){
      -- Proceed with your code --
}

Happy Coding.

You said ngModelChange didn't solved your problem. I had the same problem with Angular 9 and ngx-bootstrap 5.6.2 wich was solved changing from (bsValueChange)="onDataFinalValueChange($event)" to (ngModelChange)="onDataFinalValueChange($event)"

I worked around this problem by setting a component handleDatepickerEvents flag which starts as false and is set to true in ngAfterViewInit().

The onValueChange() function just needs to ignore changes when handleDatepickerEvents is false.

Related