angular 2 - how to set <select> default selected option
For a template driven form, I did this and got default selection.
<select [(ngModel)]="defaultOption" name="identification">
<option [value]=null>Select</option>
<option *ngFor="let option of identification" [value]="option.id"> {{ option.name }} </option>
</select>
and in the component.ts file,
identification = [
{ id: 1, name: 'Passport'},
{ id: 2, name: 'Adhaar'},
{ id: 3, name: 'Driver\'s license'},
];
defaultOption = null;
On load, we could get Select as default selected.
<select [(ngModel)]="defaultValue">
<option>AM</option>
<option>PM</option>
</select>
export class MyComponent {
defaultValue = 'PM';
}
Usually it's done like
<select [(ngModel)]="defaultValue">
<option *ngFor="let value of values" [ngValue]="value">{{value}}</option>
</select>
export class MyComponent {
values = ['AM', 'PM'];
defaultValue = this.values[1];
}
Hint For non-string values use `[ngValue]="..."
<select [(ngModel)]="defaultValue">
<option [ngValue]="values[0]">AM</option>
<option [ngValue]="values[2]">PM</option>
</select>
I don't know why so much long answers here.
Short Answer :
use [selected]="isSelected" in your option tag!
Solution :
<select>
<option [selected]="isSelected">AM</option>
<option>PM</option>
</select>
Source:
https://medium.com/@phismonster/set-default-value-for-select-in-angular-2-27f0da413935
Edit 1 : Example with array :
arr = [{str: 'A', isSelected: false},
{str: 'B', isSelected: true},
{str: 'C', isSelected: false},
{str: 'D', isSelected: false},
];
<select>
<option *ngFor="let a of arr" value="a.str" [selected]="a.isSelected">{{a.str}}</option>
</select>
link with working example : https://stackblitz.com/edit/selected-test