如何获得反应形式的先前价值?

How to get previous value of reactive form?

我有表格:

this.filterForm = this.fb.group({
      type: [null, [Validators.required]]});

我听变化:

this.filterForm.controls["type"].valueChanges.subscribe(
      selectedValue => {

});

在上面的代码中,我得到了 selectedValue 个元素,如何获取以前的值来进行比较:

if (old("type") !== selectedValue) {
   // Call user method
}

我尝试用表单中的其他两个字段执行此操作:

Observable.merge(this.filterForm.controls["classNumber"].valueChanges, this.filterForm.controls["classSuffix"].valueChanges).subscribe(response => {
        if (response[0] !== this.filterForm.value.classNumber && this.filterForm.controls["classSuffix"]) { // Call method }
    });

为什么不使用变量 oldValue?

oldValue:any;
this.filterForm.controls["type"].valueChanges.subscribe(
      selectedValue => {
           console.log(selectedValue,oldValue);
           oldValue=selectedValue; //<--give value to oldValue;
});

无论如何,在 select 值中,仅当您选择一个新值时才会发生变化(如果显示下拉列表并且 select 该值尚未 selected)

您可以使用此方法来实现您的关注:

已创建 demo 供您参考并查看 stackblitz 控制台

this.filterForm
   .controls["type"]
   .valueChanges
   .subscribe(selectedValue => {
       // New value of Type;
       console.log('New Value: ', selectedValue);

       // Old value of Type; Avoid using this.filterForm.get('type').value
       // This will give you the current/latest value.                 
       console.log('Old Value: ', this.filterForm.value['type']);   
});

我使用 to get previous value from reactive form. Pairwise 将当前值和先前值放在一个数组中并发出。