angularangular-materialangular-forms

Angular Material get previously selected value from MatSelectChange event


I am capturing MatSelectChange events from a dynamic forms library in my .ts file. This works just fine, but when I capture the event, I don't know how to acquire the previously selected value.

Getting the current value is easy, I am surprised that the prior value isn't immediately available for access.

The event contains access to $event.value and $event.source.

I have tried to dig deep into the source member, but I can't find the previous value there either as it is just the current select control.

Link to API


Solution

  • There is no way to get it from the event unfortunately. You will have to store it in a component variable, and read it from there. Which shouldn't add that much overhead, because most of the time you would have to do that anyways:

    export class SelectOverviewExample {
      selected?: string;
    
      onChange(event: MatSelectChange): void {
        console.log('Old value', this.selected);
        this.selected = event.value;
        console.log('New value', event.value);
      }
    }
    

    stackblitz