sorry for surely a dumb question already answered 1000 times maybe, but I washed the net and forums and didn’t have a CLEAR and SIMPLE answer to my quest
What I want to do :
use ion-select selector
use [(NgModel)] to store selected value
with options in an *ngFor loop
set as default value selected one of these values
I tried to use “selected” attribute in ion-select-option but does not seem to work
I tried to use the compareWith feature but didn’t manage to understand how to have it fulfill the default value stuff.
I tried to use the “value” attribute in ion-select, didn’t work either
I noticed that when I don’t use the [(NgModel)] stuff, the “value” attribute works just fine to set the default selected value, but I don’t get the utility of having a selector without storing back the selected value (or maybe there is another way, i m not an Angular guru)
Thanks forward for your help, if you could give a clear example, explained like for a 5-year old child it would be perfect.
Thing that I noticed though, is that whenever you include a [(NgModel)] inside the ion-select, this does not work anymore, and it seems to be unavoidable in Ionic 4 (really hope they will work on this !)
I found a workaround though by modifying the model inside an (ionChange) function
This gives, starting from my preceeding posted example (ensure to change MyDefaultYearIdValue type to any instead of string, didn’t figure out initially that string type wasn’t mandatory…) :
in HTML :
<ion-select (ionChange)="onSelectChange($event)" [compareWith]="compareWith" value="{{MyDefaultYearIdValue}}" >
<ion-select-option *ngFor="let year of years" value="{{year.id}}">{{year.name}}
</ion-select-option>
</ion-select>
in TS:
////// In variables definitions
SelectedYearIdValue : any ;
///// In initialisations (in my case it's in ngOnInit() function)
this.SelectedYearIdValue = this.MyDefaultYearIdValue ;
///// In functions definitions
onSelectChange(selectedValue: any) {
this.SelectedYearIdValue = selectedValue.detail.value ;
}
I would remove the selected attribute. Bottom line: only have one source of truth in any given situation. When the selected attribute is present in addition to the ngModel binding, you have two.