Set Default Value From an Array of Options in Angular We will discuss setting a default value from an array of options. First of all, we will create two variables: ngSelect , the default option for our select form, and the second will be options that will have all the values we want to display in Select options.
The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
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>
just set the value of the model to the default you want like this:
selectedWorkout = 'back'
I created a fork of @Douglas' plnkr here to demonstrate the various ways to get the desired behavior in angular2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With