Reputation: 1285
I'm trying to set up default value for my selection so I tried
[selected]= "selected_choice == 'one'"
something like this
but this didn't work.
People said [selected] no longer works so I also tried [attr.selected] but didn't work as well..
this is my whole code for one select tag
<select (change)="passValue3()" formControlName="school" class="form-control" required [(ngModel)]="selected_student" class="selectionbox">
<option *ngIf="selected_student == undefined">학년 선택</option>
<option *ngFor="let gradetype of gradeTypes" [ngValue]="gradetype" [attr.selected] = "gradetype.gradeType === 'Middle'">{{gradetype.gradeName}}</option>
</select>
How can I set up the default option for the select?
Upvotes: 6
Views: 5754
Reputation: 2033
you compare options to select by compareWith
property, If you are using angular 4, may be it will not working on angular 2.
HTML File :
<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
<option *ngFor="let animal of animals" [ngValue]="animal">
{{animal.type}}
</option>
</select>
TS File
byAnimal(item1,item2){
return item1.type == item2.type;
}
One of the best solution from this link
Upvotes: 3
Reputation: 2477
Here is my solution:
Example is about time zones. From the backend I got the next object item:
activeItem = { "timezone": { "timeZoneHolder": "Europe", "region": "Europe/Paris (CEST)", "UTC": "UTC+1" }}
And the same item from my model looks a little bit different as source is change:
{ "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }
As you see a little bit different.
So here is my model:
timeZones = [{ "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }, { "timeZoneHolder": "French Polynesia", "region": "Pacific/Gambier", "UTC": "UTC -09:00" }]
And here is the mark-up for the select, works like a charm :
<select id="timezone" name="timezone" [(ngModel)]="activeItem.timezone">
<option [ngValue]="activeItem.timezone" [selected]="true" disabled hidden>{{activeItem.timezone.region}}</option>
<option *ngFor="let timeZone of timeZones"
[ngValue]="{timeZoneHolder: timeZone.countryName, region: timeZone.timeZone, UTC: timeZone.UTC}">
{{timeZone.timeZone}}
</option>
Enjoy :)
Upvotes: 0
Reputation: 11287
You need to do something like this:
In Markup:
<select placeholder="Sample select" [(ngModel)]="selectedItem">
<option [value]="'all'">View All</option>
<option [value]="'item-1'">Item-1</option>
<option [value]="'item-2'">Item-2</option>
</select>
In Component
selectedItem='all'
Upvotes: 8