Slicc Slicc - 3 months ago 25
HTML Question

angular2 Select binding when options collection changes

I am using angular2 and have an HTML select like this:

<select class="form-control" id="myList" [(ngModel)]="mySelectedItem">
<option value="">{{ "ALL" }}</option>
<option *ngFor="let item of allItems" [value]="item">{{item}}</option>
</select>


For examples sake let myList= ["option1", "option2", "option3"]

This all works fine until the allItems collection is changed. When the user is first presented with the page, they select "option1" as their preferred option. Now the javascript modifies the allItems collection and removes "option1" as a valid option. At his point the Select shows nothing.

What I would like to happen is that the Select shows the first option "ALL" if the value is of the Select is not a known value in the AllItems collection.

The value of the myList collection are changing automatically based on some other logic in the javascript.

Can someone advise how to achieve this?

Answer

You may try below,

 import { Component }  from '@angular/core';

 @Component({
   selector: 'my-app',
   template: `<h3 class="title">Basic Angular 2</h3>
   <hr />
   <select class="form-control" id="myList" [(ngModel)]="mySelectedItem">
    <option value="all">{{ "ALL" }}</option>
    <option *ngFor="let item of allItems" [value]="item">{{item}}</option>
   </select>
   <button (click)="updateLIst()" >Update</button>
  `
 })
 export class AppComponent {
   mySelectedItem= 'all'
   allItems  = ["option1", "option2", "option3"];
   constructor(){}

   updateLIst(){
     this.allItems  = [ "option2", "option3"];
     this.mySelectedItem = 'all';
   }
 }

wherever allItems changes set mySelectedItem to all in your java script code.

Here is the Plunker!!

Hope this helps!!