Search code examples
htmlcssangularjsangulardropdownbox

Default value of dropdown box not showing in Angular 2


I am trying to display "Select a color" as the default value in my dropdown box. After selecting the color I want this option to not be available.

Below is the code I am using:

<select class="color-filter" [(ngModel)] = "selectedColor">
     <option disabled selected value class="hideoption">Select a Color</option>
     <option *ngFor="let c of color | mapToIterable" [value]="c.key">{{c.val}}</option>
</select>

CSS:

 .hideoption { display:none; visibility:hidden; height:0; font-size:0; }

Without including ngModel this works fine. However when I include ngModel it shows no default text in my dropdown box.


Solution

  • That is because the model selectedColor is empty, and angular select the option selected in the ngModel, in your case is undefined, and angular search that value and it don't found nothing.

    You should put a default value to the default option and put that value to the model.

    Like this:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <select class="color-filter" [(ngModel)] = "selectedColor">
         <option disabled value="0" class="hideoption">Select a Color</option>
         <option *ngFor="let c of color" [value]="c">{{c}}</option>
    </select>  
      `,
      styles: [`
      .hideoption { display:none; visibility:hidden; height:0; font-size:0; }
      `]
    })
    export class AppComponent {
      selectedColor:any = 0;
      color;
    
      constructor(){
        this.color = [
          "red","blue"
        ]
      }
    }
    

    You can seem it in this Plunker, enjoy.