首页 > 解决方案 > 如何在 Angular 10 中获取下拉列表的新旧值

问题描述

我对角度非常陌生,仍处于基本阶段。

选择下拉列表时,我试图同时获取旧值和新值,但不知道该怎么做。我能够获得新价值,但不能获得旧价值。

需要将旧值和新值都传递给 Angular 函数。

body.component.html:

<div class="container">
<mat-label>Destination 1</mat-label>
<mat-select #box (selectionChange)="removeFromPlanet(box.oldValue, box.newValue)">
  <mat-option *ngFor="let planet of planets" [value]="planet">
    {{ planet }}
  </mat-option>
</mat-select>

body.component.ts:

removeFromPlanet(old, new) {
console.log(old, new);}

但它不起作用。我在哪里做错了?

标签: javascripthtmlangularangular-materialangular-ui

解决方案


您可以通过将值推送到主题中来处理先前值和当前值,并使用成对运算符观察此主题。此运算符将发出流的先前值和当前值。(https://www.learnrxjs.io/operators/combination/pairwise.html

例子:

export class YOU_COMPONENT{

  private data: Subject<any> = new Subject<any>();

  checkTitle(value){
    this.data.next(value);
  }

  observeDataChange():Observable<[]>{
     // this return an observable of an array that contains [previous, current] data
     return this.data.asObservable().pipe(pairwise());
  }

}

推荐阅读