Angular 2 Dropdown Options Default Value Angular 2 Dropdown Options Default Value angular angular

Angular 2 Dropdown Options Default Value


Add a binding to the selected property, like this:

<option *ngFor="#workout of workouts"     [selected]="workout.name == 'back'">{{workout.name}}</option>


If you assign the default value to selectedWorkout and use [ngValue] (which allows to use objects as value - otherwise only string is supported) then it should just do what you want:

<select class="form-control" name="sel"     [(ngModel)]="selectedWorkout"     (ngModelChange)="updateWorkout($event)">  <option *ngFor="let workout of workouts" [ngValue]="workout">    {{workout.name}}  </option></select>

Ensure that the value you assign to selectedWorkout is the same instance than the one used in workouts. Another object instance even with the same properties and values won't be recognized. Only object identity is checked.

update

Angular added support for compareWith, that makes it easier to set the default value when [ngValue] is used (for object values)

From the docs https://angular.io/api/forms/SelectControlValueAccessor

<select [compareWith]="compareFn"  [(ngModel)]="selectedCountries">    <option *ngFor="let country of countries" [ngValue]="country">        {{country.name}}    </option></select>
compareFn(c1: Country, c2: Country): boolean {    return c1 && c2 ? c1.id === c2.id : c1 === c2;}

This way a different (new) object instance can be set as default value and compareFn is used to figure out if they should be considered equal (for example if the id property is the same.


Add this Code at o position of the select list.

<option [ngValue]="undefined" selected>Select</option>