I'm using Ionic 4.
I want to show a default value in ion-select-option.
Option's values come from the server.
API works all values show but on click of ion-select.
But I want to show the default value.
I have already initialized userData.business_type in the constructor.
I have updated my question you can see that.
when my page load no value shown in ion-select only drop-down button show but when I click on the drop-down button then value shown.
But I want to show the first value by default when page visible to the user.
Response
{"success":1,"service_details":[{"id":"1","name":"Job\/Service","status":"1"},
{"id":"2","name":"Student","status":"1"},{"id":"3","name":"House Wife","status":"1"},{"id":"4","name":"Business","status":"1"}]}
register.ts
userData = { "fname": "", "lname": "", "contact_no": "", "email_id": "", "password": "",
"business_type": "", "organization_name": "", "designation": "", };
constructor () {
this.userData.business_type = "1";
}
getAllService(){
let loading = this.loadingCtrl.create({
spinner: 'circles',
message: 'Please wait...'
}).then(loading => loading.present());
this.authService.getData("get_all_service_type.php").then((result) => {
this.items = result;
this.success = this.items.success;
console.log(this.success);
if (this.success == 1) {
this.loadingCtrl.dismiss();
this.serviceData = this.items.service_details;
console.log(this.serviceData);
} else {
this.message = this.items.message;
this.loadingCtrl.dismiss();
}
}, (err) => {
this.loadingCtrl.dismiss();
console.log("Error", err);
});
}
register.html
<ion-item>
<ion-label>Occupation </ion-label>
<ion-select value="Job/Service" (ionChange)="optionsFn()" name="business_type" [(ngModel)]="userData.business_type">
<div *ngFor="let item of serviceData">
<ion-select-option value="{{item.id}}">{{item.name}}
</ion-select-option>
</div>
</ion-select>
</ion-item>
OR
<ion-item>
<ion-label>Occupation</ion-label>
<ion-select value="1" (ionChange)="optionsFn()" name="business_type" [(ngModel)]="userData.business_type">
<ion-select-option *ngFor="let item of serviceData" value="{{item.id}}" [selected]="userData.business_type == item.name">{{item.name}}</ion-select-option>
</ion-select>
</ion-item>
Your userData.business_type: ''
has an empty value. If you want a default value, set this with a known default value.
// set business_type here
userData = { "fname": "", "lname": "", "contact_no": "", "email_id": "", "password": "",
"business_type": "1", "organization_name": "", "designation": "", };
constructor() {}
Also remove the unnecessary <div>
in your html template.
<ion-item>
<ion-label>Occupation </ion-label>
<ion-select (ionChange)="optionsFn()" name="business_type" [(ngModel)]="userData.business_type">
<ion-select-option *ngFor="let item of serviceData" value="{{item.id}}">
{{item.name}}
</ion-select-option>
</ion-select>
</ion-item>