如何从 Angular mat-select 获取以前的和新的值?

Rey*_*ali 2 angular-material angular

你好。我正在使用 angular 6 和 angular 材料,并且我有一个字符串数组,我将其显示在 mat-select 表单字段中。如果用户选择一个元素,然后选择另一个,我需要跟踪什么是以前的值,什么是新值。

到目前为止,我已经能够使用 $event.value 获取当前值,但是我还没有找到存储或获取先前值的方法。

   <mat-select  placeholder="Choose..." (selectionChange) ="checkTitle($event.value);">
            <mat-option *ngFor="let option of Titles; trackBy: trackByFn" [value]="option.title">
              {{option.title}}
            </mat-option>
    </mat-select>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我还没有想出如何解决这个问题的任何想法。帮助表示赞赏。

Eli*_*seo 7

补充赛义夫杰布的回答,如果你使用 formControl 或 FormGroup 来获取/放置值,你可以使用 formControl.valueChanges,那就是

  <mat-select [formControl]="control">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>

  control=new FormControl()

  ngOnInit()
  {
    this.control.valueChanges.pipe(
      startWith(this.control.value),
      pairwise()
    ).subscribe(
      ([old,value])=>{
        console.log(old,value)
      }
    )
  }
Run Code Online (Sandbox Code Playgroud)

第一个更改需要 startWith(this.control.value) 发出值

堆栈闪电战


Sai*_*rbi 5

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

}



Run Code Online (Sandbox Code Playgroud)


Hos*_*avi 5

另一个简单的解决方法是使用openedChangefrommat-select本身并保存当前值。openedChange当 mat-select 打开时会发出数据,它是event一个布尔值。

public onMatSelectOpen(form: AbstractControl): void {
  this.prevMatSelectValue = form.value.type;
}

public onMatSelectValueChanges(event): void {
  this.currentValue = event.value
}
Run Code Online (Sandbox Code Playgroud)
<mat-form-field appearance="outline">
  <mat-label>label</mat-label>
  <mat-select 
    formControlName="item"
    (openedChange)="onMatSelectOpen(form)"
    (selectionChange)="onMatSelectValueChanges($event)"
  >
  <mat-option *ngFor="let item of items" [value]="item.id">
      {{ item.name }}
  </mat-option>
  </mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

要获取当前值,您可以使用selectionChangefrom mat-select。