Search code examples
htmlangular6placeholderngforngmodel

Cannot integrate a place holder in a dropdown menu when using ngModel


I have a dropdown menu using an *ngFor loop and all the options are data bound. I'm trying to put a placeholder in until one option is selected and if I use the first set of code the placeholder appears perfectly but when I include the [(ngModel)] (which I need) the placeholder disappears.

Note: The ngModel is bound to the index of the dropdown so I can use that to filter a JSON file, which is why I also have an index running.

I've tried using 'placeholder' and 'required placeholder' and adding an initial option in before the for loop options

HTML Code with working placeholder but no ngModel

  <label for="filter-coach-sel">Option</label>
    <select required placeholder=""  class="form-control" id="filter-coach-sel"  >   
        <option hidden value="" disabled selected>Select an option </option>         
      <option *ngFor = " let coach of navHistory;">{{coach.account.name}}</option>                   
  </select>

HTML Code with ngModel but placeholder no longer works

            <div class="form-group">    
              <label for="filter-coach-sel">Coach</label>
                <select required placeholder="" [(ngModel)]="selectedCoachIndex" (change) = "changeCoach()" class="form-control" id="filter-coach-sel"  >   
                   <option   disabled selected>Select one category </option>         
                  <option *ngFor = " let coach of navHistory; let i = index"  value="{{i}}"> {{coach.account.first_name}}</option>                   
             </select>
            </div>


Solution

  • Since you are using ngModel to bind the select box, your placeholder option also needs to be one among the value. Try initializing as selectedCoachIndex=""; as assigning value="" for your option

    <div class="form-group">
        <label for="filter-coach-sel">Coach</label>
      <select [(ngModel)]="selectedCoachIndex" class="form-control"  >   
        <option disabled selected value="">Select one category </option>        
        <option *ngFor = " let coach of navHistory; let i = index"  value="{{i}}"> {{coach.first_name}}</option>                   
      </select>
    </div>
    

    And your .ts file would have something like this

    navHistory = [{
        first_name: 'Bob'
      },{
        first_name: 'Jon'
      },{
        first_name: 'Mat'
      }];
    selectedCoachIndex = "";
    

    Stackblitz Demo