angularmd-select

How to get previous value of md-select in Angular


I have this md-select

<md-select
      class="pull-right"
      [options]="nodeNames"
      (handleChange)="onChange($event)"
      optionLabel="name"
      overlayClass="common-md-select-drop-down"
      scrollHeight="350px"
      [(ngModel)]="selectedServer"
    >
</md-select>

And in my .ts file, my onChange function looks like this:

public onChange(event): void {
    this.selectedServer = event.value.name;
    this.getJobStatusData(this.selectedServer);
}

So, what I want is when I have selected an item from the dropdown and I navigate to some other component and come back to this component, I want the dropdown to have the previously selected value. So, in my case, selectedServer contains the selected value. How do I do that?

EDIT 1

<md-select
      class="pull-right"
      [options]="nodeNames"
      (handleChange)="onChange($event)"
      optionLabel="name"
      overlayClass="common-md-select-drop-down"
      scrollHeight="350px"
      [(ngModel)]="selectedServer"
      (ngModelChange)="onModelChange(selectedServer, $event); selectedServer = $event;"
    >
    </md-select>

Solution

  • Simplest solution would be to use localStorage for this purpose:

    Store the value in localStorage and when navigate to same component, just read that value and set:

       public onChange(event): void {
        localStorage.setItem('selectedServer' : event.value.name);
        this.selectedServer = event.value.name;
        this.getJobStatusData(this.selectedServer);
       }
    

    Now in the ngOninit of the component:

    this.selectedServer = localStorage.getItem('selectedServer') || '';