Reputation: 2034
In my angular value i have a select for changing timezone. this.userTimeZone is an object in my component.
{
AdjustmentRules:null
BaseUtcOffset:"-04:30:00"
DaylightName:"Venezuela Daylight Time"
DisplayName:"(UTC-04:30) Caracas"
Id:"Venezuela Standard Time"
StandardName:"Venezuela Standard Time"
SupportsDaylightSavingTime:false}
My select option looks like this:
<select name="timeZones" [(ngModel)]="userTimeZone" (change)="setTimezoneId($event)" class="form-control">
<option *ngFor="let time of timezones" [ngValue]="time">{{time.DisplayName}}</option>
</select>
I'm unable to set the initial value of the select.
Though userTimeZone has a value the select shows blank on loading.
If i give userTimeZone.Id and [ngValue]="time.id" the option gets selected but then the value returned on change is only the id and not the whole object.
I want the entire object when the select option changes ans also set the initial value of the select.
No sure what's is wrong here.Please guide
Thanks
Upvotes: 0
Views: 1437
Reputation: 2034
So below is what i did
<select name="timeZones" [(ngModel)]="userTimeZone.Id" (change)="setTimezoneId($event)" class="form-control">
<option *ngFor="let time of timezones" [value]="time.Id"> {{time.DisplayName}} </option>
</select>
userTimeZone.Id will match with time.Id and the default option will get selected.
In the change method we filter the object from the json based on the value
setTimezoneId(event:any) {
/*Filter object from the json */
this.userTimeZone = this.timezones.filter(function (zone: any) {
return zone.Id == event.target.value;
})[0];
console.log(this.userTimeZone);
}
Upvotes: 1
Reputation: 478
You need to use [attr.value]
in your options and make sure that the value of your options is NOT an object, you can use and string and then match with the object in the collection if you need.
Check app.ts
in this example:
https://plnkr.co/edit/gvc5bf50sgA57Y0YGRui
Upvotes: 0
Reputation: 11184
Try this :
use (ngModelChange)="setTimezoneId($event)" instead of (change)="setTimezoneId($event)"
<select name="timeZones" [(ngModel)]="userTimeZone" (ngModelChange)="setTimezoneId($event)" class="form-control">
<option *ngFor="let time of timezones" [ngValue]="time">{{time.DisplayName}}</option>
</select>
Upvotes: 0