Angular 2 - setting default value in dropdown when default is hard coded

Jhorra picture Jhorra · Jan 12, 2017 · Viewed 17.4k times · Source

I have the following dropdown. I want to set All Patients as the default value.

    <select [(ngModel)]="searchModel.careprovider">
      <option [value]="0">All Pateints</option>
      <option *ngFor="let user of practiceUsers" [value]="user._id.$oid">
        {{user.dn}}
      </option>
    </select>

My model is declared this way:

searchModel: any = { location: null, practice: null, name: '', careProvider: 0 };

I set the practiceUsers this way:

  this._practice.getUsers(this.searchModel.practice).subscribe(result => {
    this.practiceUsers = result;
    this.searchModel.careProvider = 0;
  });

No matter how I change it I always just get a blank option as the default. I've tried adding an object to the this.practiceUsers array after it is loaded, then setting the model value. I've tried setting the model value with and without quotes to see if a number or string made a difference. Everything I try still results in the default being the blank option.

In Angular 1 I would have used ng-options, but that is no longer available for Angular 2, and every example I find shows to use the ngFor for dropdowns.

Answer

Stefan Svrkota picture Stefan Svrkota · Jan 12, 2017

Object attributes are case sensitive, in your object, attribute is called careProvider, but in your template, you are using searchModel.careprovider with lowercase p. I think you also have to use NgValue directive instead of value because you are using NgModel directive. So, this should work: it is not working

<select [(ngModel)]="searchModel.careProvider">
  <option [ngValue]="0">All Pateints</option>
  <option *ngFor="let user of practiceUsers" [ngValue]="user._id.$oid">
    {{user.dn}}
  </option>
</select>