首页 > 解决方案 > 在(更改)事件回调上具有旧值的角反应形式

问题描述

考虑一个带有输入的 Angular 响应式表单。每当输入发生变化时,我们都希望保留它的旧值并在某个地方显示它。以下代码显示如下:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  name = 'Reactive Form';
  changedValue;
  oldValue;
  ooldValue;
  rform = new FormGroup({
    inputOne: new FormControl('chang me')
  });


  onOneChange(event) {
    this.changedValue = event.target.value;
    console.log('oneChanged', this.changedValue, 'old value is', this.oldValue);
    this.ooldValue = this.oldValue;
    setTimeout( ()=>this.oldValue = this.changedValue, 1);
  }
}
<form [formGroup]="rform">
    <label>
      One:
      <input formControlName="inputOne" (change)="onOneChange($event)"/>
    </label>
  </form>
  <p>
    changed value: {{changedValue}}
  </p>
  <p>
        old value: {{ooldValue}}
  </p>

正如您所看到的,它已通过在代码中保留三个变量来解决,这是不可取的(是的,changedValue可以删除变量,但仍然保留两个变量来保留旧值很烦人,不是吗?)。

有没有办法用更少的变量重写代码?Angular 本身是否有一种下降的方式来做到这一点?

你可以在这里找到代码

标签: javascriptangularangular2-formsangular-reactive-formsangular-event-emitter

解决方案


valueChanges 是一个 Observable,因此您可以通过管道成对获取订阅中的上一个和下一个值。

// No initial value. Will emit only after second character entered
this.form.get('inputOne')
  .valueChanges
  .pipe(pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );
// Fill buffer with initial value, and it will emit immediately on value change
this.form.get('inputOne')
  .valueChanges
  .pipe(startWith(null), pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );

推荐阅读