[Fixed] Old value kept on ngModel change

Issue

Dealing with a table which need a filter by data, I’ve created the following screen:

enter image description here

What I need is to remove values outside the date start criteria of the filter so I’ve done this on my EsightComponent:

startDateChange($event, dt, col) {
  this.loading = true;
  this.eSightEndSubscription = this.eSightService.getByContractId(this.contractId).subscribe(
    res => {
      const filterResults = this.reads.filter((read) => {
        const iteratorDate = new Date(20 + read.timestamp.slice(-2), read.timestamp.slice(0, 2) - 1, 1);
        console.log(this.startDateFilter);
        return iteratorDate <= this.startDateFilter;
      }, this);

      this.processRightAnswer(filterResults);
    },
    error => {
      console.log('ERROR');
    },
    () => {
      this.loading = false;
    });
}

And this is my view:

<h4>Lecturas eSight <small>contrato {{ contractId }}</small></h4>

<p-calendar dateFormat="mm/yy" [(ngModel)]="startDateFilter" (onBlur)="startDateChange($event, dt, col)"></p-calendar>
<p-calendar [(ngModel)]="endDateFilter" (change)="startDateChange($event, dt, col)"></p-calendar>

<p-dataTable [value]="reads" [rows]="30" [paginator]="true" [loading]="loading" selectionMode="single" scrollable="true" #dt>
  <ng-container *ngFor="let col of cols; let i = index;">
    <p-column [field]="col.field" [header]="col.header" *ngIf="i === 0" [style]="{ 'width': '170px' }">
    </p-column>
    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length <= 10" [style]="{ 'width': '55px' }"></p-column>
    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length > 10" [style]="{ 'width': '170px' }"></p-column>
  </ng-container>
</p-dataTable>

<button class="btn btn-warning" (click)="onReturn()">AtrĂ¡s</button>

Based on tho way data binding principle, this.startDateFilter should catch changes on it, but it doesn’t. If I select a date on the calendar, it always displays the previous value, not the selected new one. That is seen on console.log(this.startDateFilter) line.

I’ve checked I could use ngOnChanges to catch changes and to have access to both old and new values, but this hook just works for @Input() values and this is not my case.

I wish to retrieve the value selected by the user and not an old one.

Thanks.

Solution

It’s happens because ngModel triggers after change datection, but you are watching for blur, that fires before detection

You should getting current value from $event, not from model value.
Something line

$event.value

Leave a Reply

(*) Required, Your email will not be published