Search code examples
angularangular7angular-ngmodel

Select - Setting a disabled selected option as well as having a bound *ngfor option


I have a piece of code that's not behaving the way I want it to.

Basically I want to have the "Please select a team" value to come up as the default selected option so I don't have to have a visible label assigned to the dropdown (I hope that makes sense).

The code works ok in so much as the team values appear and the "Please select a Team" appears, however the drop down selects the first element of the *ngfor option not the "Please select a Team" option

Can anybody shed some light on this please? I'm pretty new to Angular so be gentle.

<label for="team" class="sr-only">Team </label>
  <select [(ngModel)]="model" autocomplete="off" required>
      <option value="default" disabled selected>Please select a 
Team</option>
      <option *ngFor="let team of teams" [value]="team.name"> {{team.name}}</option>
  </select>

Solution

  • You need to use Angular's data binding for the value attribute. Change value="default" to [value]="default". Also be sure to read this Angular doc to learn more about data binding

    Take a look at this stackblitz and let me know if this is your expected result