How to obtain previous and new value from Angular mat-select?

ⅰ亾dé卋堺 提交于 2020-02-04 04:01:29

问题


Hellow. I'm using angular 6, and agular material, and I have an array of strings, which I display in a mat-select form field. If an user selects one element, and then another, I need to track what was the previous value and what is the new value.

So far, I've been able to obtain current value using $event.value, but I haven't found a way to store or obtain what the previous value was.

   <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>

So far, I haven't come up with any ideas as to how solve this problem. Help is appreciated.


回答1:


You can handle previous and current value by pushing the value into a Subject, and observe this Subject using the pairwise operator. This operator will emit the previous and the current value of the stream. (https://www.learnrxjs.io/operators/combination/pairwise.html)

example:


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

}






回答2:


Complementary the Saif Jeb's answer, if you use a formControl or FormGroup to get/put the value, you can use formControl.valueChanges, that's

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

It's necesary a startWith(this.control.value) for the first change emit the value

See stackblitz




回答3:


You could just simply have a variable, to which you store the previous value:

prevVal: string;

checkTitle(newVal) {
  if (this.prevVal) {
    console.log(this.prevVal, newVal);
    // do stuff
  }
  // after processing, store the new val as the prev val
  this.prevVal = val;
}



回答4:


There's a property for MatList [selected], which takes boolean value as in true or false.

So while updating or selecting a value. Create a key-value pair which will on selection set true.



来源:https://stackoverflow.com/questions/57513082/how-to-obtain-previous-and-new-value-from-angular-mat-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!