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
?
If you are using form there should be
name
field insideselect
tag.All you need to do is just add
value
to theoption
tag.selectedWorkout
value should be "back" , and its done.Add this Code at o position of the select list.
<option [ngValue]="undefined" selected>Select</option>
I faced this Issue before and I fixed it with vary simple workaround way
For your Component.html
Then in your component.ts you can detect the selected option by
You Can do this way
or this way
or you can set deafult vlaue this way
or
If you don't want the 2-way binding via [(ngModel)], do this:
Just tested on my project on Angular 4 and it works! The accountsList is an array of Account objects in which name is a property of Account.
Interesting observation:
[ngValue]="acct" exerts the same result as [ngValue]="acct.name".
Don't know how Angular 4 accomplish it!
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:Ensure that the value you assign to
selectedWorkout
is the same instance than the one used inworkouts
. 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
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 theid
property is the same.