Angular: Updating <select> array options, and retaining selected value

Viewed 549

A question about <select> + updating the array of options. I'm wanting to update the options available - but leave the current value selected if it's still available.

I'm finding that NG creates a new index when it believes the object is new (pictured) - which no longer matches the selected option (which appears to be a primitive in the code - but not the view).

enter image description here

And as I want to fire an API event for each actual change - I'd like to avoid firing a request for any intermediate steps in the processing...

I've created an example plnker: https://plnkr.co/edit/VYYTvZ?p=preview

The main bits being:

The select box is pretty simple:

<select
  [(ngModel)]="selectedOption">
  <option
    *ngFor="let option of optionsList"
    [ngValue]="option.value">
      {{ option.name }}
  </option>
</select>

And this is my example code of updating the options array. (The clone is performed to mimic the API coming back with a new object...)

public get selectedOption (): string  {
    return this._selectedOption;
  }

  public set selectedOption (value: string) {
    // This is a mock for something that would make an API request on every change...
    this.logUpdates.push(`Updated: '${value}'`);

    this._selectedOption = value
  }

  private list1 = [
    { name: 'one', value: 1 },
    { name: 'two', value: 2 },
    { name: 'three', value: 3 },
    { name: 'four', value: 4 }
    ];

  private list2 = [
    { name: 'two', value: 2 },
    { name: 'four', value: 4 },
    { name: 'six', value: 6 },
    { name: 'eight', value: 8 }
    ];

  public loadList1 () {
    let clone = this.list1.slice(0);
    this.optionsList = clone
  }

  public loadList2 () {
    let clone = this.list2.slice(0);
    this.optionsList = clone;
  }

I'm wondering if the correct solution is to update the array in place? (And is there a tool/feature that would assist this?) Or save + restore the value (and somehow block it firing too many API requests)? Or am I just doing the select/options wrong?

Thanks.

0 Answers
Related