Angular 2 Dropdown Options Default Value

ClickThisNick picture ClickThisNick · Mar 14, 2016 · Viewed 262.2k times · Source

In Angular 1 I could select the default option for a drop down box using the following:

<select 
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>

In Angular 2 I have:

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

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?

Answer

Douglas picture Douglas · Mar 14, 2016

Add a binding to the selected property, like this:

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