Slicc Slicc -4 years ago 283
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>

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 Source

You may try below,

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

   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>
   <button (click)="updateLIst()" >Update</button>
 export class AppComponent {
   mySelectedItem= 'all'
   allItems  = ["option1", "option2", "option3"];

     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!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download