简体   繁体   中英

Old value kept on ngModel change

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

在此处输入图片说明

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.

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

基于 DmitriyKhirniy 的回答(非常感谢!!!),最终有效的是:

$event.target.value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM