【问题标题】:How to get previous value of reactive form?如何获得反应形式的先前值?
【发布时间】:2019-05-03 07:51:03
【问题描述】:

我有表格:

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 }
    });

【问题讨论】:

标签: angular angular-reactive-forms


【解决方案1】:

为什么不使用变量 oldValue?

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

无论如何,只有在您选择新值时才会在选择值中发生更改(如果显示下拉菜单并选择尚未选择的值,则不会发生)

【讨论】:

    【解决方案2】:

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

    已创建 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']);   
    });
    

    【讨论】:

    • 关键注释不在代码 sn-p 范围内 - 避免使用 this.filterForm.get('type').value - 这将为您提供当前/最新值。
    【解决方案3】:

    我使用this solution 从响应式表单中获取先前的值。 Pairwise 将当前值和先前值放在一个数组中并发出。

    【讨论】:

    • this.form.value['type'] 对我不起作用。上面的解决方案成功了。
    • 这应该是公认的答案。
    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 2019-07-07
    • 2017-11-08
    • 2018-07-06
    • 2018-08-20
    • 2013-05-16
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多