Reputation: 22568
Struggling to set the default option in an <ion-select>
control. Using v4 rc2 but this has been an issue since I started with the late v4 betas.
The <ion-select>
correctly sets the default selection but I get the small down caret. The selected option is not displayed. When I select the control, the alert is displayed and the correct option is selected. Or am I doing something wrong?
Does the order of setting the measureSetId
vs loading the measureSets[]
matter?
Thoughts? appreciate any help on this.
<ion-select name="measureSetSelect" [(ngModel)]="selectedMeasureSetId">
<ion-select-option *ngFor="let measureSet of measureSets" [value]="measureSet.measureSetId">
{{measureSet.name}}
</ion-select-option>
</ion-select>
public measureSets: IMeasureSet[];
public selectedMeasureSetId: number;
ngOnInit() {
this.measureSetsApiService.query().pipe(take(1)).subscribe(result => {
this.selectedMeasureSetId = result.find(i => i.isDefault).measureSetId || 1;
this.measureSets = result;
});
}
Upvotes: 4
Views: 8869
Reputation: 5289
When the options
list contains objects, you need to use [ngValue]
and [compareWith]
Try this code:
<ion-select name="measureSetSelect" [(ngModel)]="selectedMeasureSet" [compareWith]="compareById">
<ion-select-option *ngFor="let measureSet of measureSets" [ngValue]="measureSet">
{{measureSet.name}}
</ion-select-option>
</ion-select>
In your Component:
compareById(o1, o2) {
return o1.id === o2.id
}
Update to component part to set the ngModel to object:
public selectedMeasureSet: IMeasureSet;
ngOnInit() {
this.measureSetsApiService.query().pipe(take(1)).subscribe(result => {
this.selectedMeasureSet = result.find(i => i.isDefault) || result.find(i => i.id === 1);
this.measureSets = result;
});
}
Also consider referring this document for further reading on it: https://medium.com/@kastepanyan24/how-to-set-selected-option-dynamically-in-angular-6-85c99958cca5
Upvotes: 2