Search code examples
angularasynchronousangular-ngmodel

How can I use the ngModel old value in a function if the value is asynchronous?


I have an input (dropdown) where upon getting a new input, I want to check something about both the old and the new input. However, I have the data (old input) only in an async format.

<p-dropdown [options]="valueOptions" [ngModel]="storeValue$ | async"
 (ngModelChange)="checkChange($event, ???)" </p-dropwdown>

if the old value were not async, I could do the following :

<p-dropdown [options]="valueOptions" [ngModel]="storeValue"
 (ngModelChange)="checkChange($event, storeValue)" </p-dropwdown>

or if the store value were not nullable, I could do

<p-dropdown *ngIf="storeValue$ | async as val" [options]="valueOptions" [ngModel]="val"
 (ngModelChange)="checkChange($event, val)" </p-dropwdown>

Given that the value is nullable and that it is also async, how can I access it in the checkChange function?


Solution

  • You can use tap operator to store the initial value. then you can compare with current value.

    component.ts

    storeValue$.pipe(tap(value=>this.initialValue = value));
    
    checkChange(newValue){
        this.initialValue === newValue;
    }