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
?
Add on to @Matthijs 's answer, please make sure your
select
element has aname
attribute and itsname
is unique in your html template. Angular 2 is using input name to update changes. Thus, if there are duplicated names or there is no name attached to input element, the binding will fail.According to https://angular.io/api/forms/SelectControlValueAccessor you just need the following:
theView.html:
theComponent.ts
Add binding property selected, but make sure to make it null, for other fields e.g:
Now it will work
You can Use that
[ngModel]
instead of[(ngModel)]
and it is OkYou can do as above:
In above code as you can see, selected attribute of the repeating option is set on checking index of the repeating loop of list. [attr.< html attribute name >] is used for setting html attribute in angular2.
Another approach will be setting model value in typescript file as :