如果值是异步的,如何在函数中使用 ngModel 旧值?

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

我有一个输入 (dropdown),在获得新输入后,我想检查一些关于旧输入和新输入的信息。但是,我只有异步格式的数据(旧输入)。

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

如果旧值不是异步的,我可以执行以下操作:

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

或者如果存储值不可为空,我可以这样做

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

鉴于值 可以为 null 并且它也是异步的,我如何在 checkChange 函数中访问它?

您可以使用tap运算符来存储初始值。然后你可以与当前值进行比较。

component.ts

storeValue$.pipe(tap(value=>this.initialValue = value));

checkChange(newValue){
    this.initialValue === newValue;
}