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

Issue

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.

Solution

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

}



Answered By – Saif Jerbi

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.