0

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>
ChrisF
  • 134,786
  • 31
  • 255
  • 325
pranami
  • 1,381
  • 5
  • 22
  • 43
  • 1
    You can create a service that can hold the state of selectedServer. Something like this maybe https://stackoverflow.com/questions/47162939/how-to-retain-a-selected-value-while-going-through-the-router-in-angular – amnah Aug 16 '21 at 11:55

1 Answers1

2

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') || '';
Ritesh Waghela
  • 3,474
  • 2
  • 19
  • 25