Search code examples
javascriptangulartypescriptangular-forms

Select box not showing the selected option first


I am using angular 6 and i am unable to display the selected option as default in select box,

HTML consists,

<select class="form-control selectBox" name="username" #username="ngModel" required ngModel>
<option disabled selected>Select User Name</option>
<option *ngFor="let user of userList" [value]="user.uid">{{user.name }}</option>
</select>

Ts:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  userList: any = [
    {
      "name" : "Test User"
    },
    {
      "name" : "Hello World"
    },
    {
      "name" : "User Three"
    }
  ]
}

It is showing empty value as default inside the select box.

How can i show the selected option as default inside the select box which from the line?

<option disabled selected>Select User Name</option>

Stackblitz:https://stackblitz.com/edit/angular-wfjmlm


Solution

  • You need to set a value in select box like this:

    <option disabled selected value="">Select User Name</option>
    

    Will make it work.