Select Box default value is not showing with [(ngModel)] Angular 2

Ambuj Khanna picture Ambuj Khanna · Aug 14, 2018 · Viewed 7.3k times · Source

I am using below snippet in my code. If I am applying variable binding "[(ngModel)]" then my default option i.e. "Title*" is not visible. If i remove it then it behave normally and star showing 1st option by default selected.

 <select name="title" id="title"title="Please select title" [(ngModel)]="title">
                <option value="title" selected>Title*</option>
                <option value="MD">MD</option>
                <option value="RN">RN</option>
                <option value="Mr">Mr</option>
                <option value="Ms">Ms</option>
  </select>

Answer

Keshan Nageswaran picture Keshan Nageswaran · Aug 14, 2018

property/ngmodel title need to be set in your component's class to the title element that you want to be pre-selected from titles list. Eg:

HTML

<h1>Selection</h1>
<select type="number" [(ngModel)]="title" >
  <option *ngFor="let titl of titles" [ngValue]="titl.name">{{titl.name}}</option>
</select>
{{title}}

Component

export class AppComponent  {
  title:string;
  titles:Array<Object> = [
      {name: "Title*"},
      {name: "MD"},
      {name: "RN"},
      {name: "Mr"},
      {name: "Ms"}
  ];
constructor() {
    //Old Code
   // this.title = this.titles[0]name;

  //New Code
  this.title = this.titles[0]['name'];
  }

}

Demo