Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 998
Ambuj Khanna Avatar asked Dec 05 '22 11:12

Ambuj Khanna


1 Answers

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

like image 116
Keshan Nageswaran Avatar answered Dec 09 '22 13:12

Keshan Nageswaran