如何在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);}

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

解决方法

您可以通过将值推入主题来处理先前和当前值,并使用成对运算符观察此主题。此运算符将发出流的前一个值和当前值。 (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());
  }

}