How to select <ion option> if there is only a single value?

Friends,
I have a form in that some time the code

<ion-select formControlName="zonaloffice" [(ngModel)]="data.zonaloffice"> 
        <ion-option *ngFor="let zonaloffice of zonaloffices" value="{{zonaloffice.zonal_id}}">
            {{zonaloffice.zonal_name_eng}}
        </ion-option>
        </ion-select>

have only one value for selection (in 98% cases) with label “Main Office”. In that situation I plan to select that field automatically when that page is loaded to avoid user difficulty.
Please suggest a method …

Thanks

Anes

@anespa what’s the module code look like? Do you have a default value for data.zonaloffice?

No there is no default value … But most cases the label value is “Main Office”…

You’ll need to set a value in your module code, e.g. data: { zonaloffice: "My Default value" }, then your select component would have that option selected by default – assuming the value matches the value of an ion-option

If I understand the question properly, you want to select the option if it contains the option “Main Office”.

Assuming that this requirement is always static, you can set it as selected with and if statement using [selected]="zonaloffice.zonal_name_eng == 'Main Office'". Either using the zonaloffice.zonal_name_eng or zonaloffice.zonal_id, I suggest using the id if you know which one its going to be, if not you can use the name like so:

<ion-select formControlName="zonaloffice" [(ngModel)]="data.zonaloffice"> 
        <ion-option *ngFor="let zonaloffice of zonaloffices" value="{{zonaloffice.zonal_id}} [selected]="zonaloffice.zonal_name_eng == 'Main Office'">
            {{zonaloffice.zonal_name_eng}}
        </ion-option>
</ion-select>

Hope It helps. Cheers

Dear @L96Ionic

I have one more condition , if there is only one value in option that is “Main Office” then select it . If more than one select option no need to select. In your case that may select in all cases…
Please consider that case and advise

Thanks

Anes

Just replace [selected]="…" with:

[selected]="zonaloffices.length == 1 && zonaloffice.zonal_name_eng == 'Main Office'

It is same as doing it at TS side:

if(
      this.zonaloffices.length == 1
      && this.zonaloffices[0].zonal_name_eng == "Main Office"
    ){
      this.data.zonaloffice = this.zonaloffices[0].zonal_id;
    }
2 Likes

Dear @sonicwong78

The TS Script works fine … Thanks alot…

But there is one typo , the exact working code is:

if(
      this.zonaloffices.length == 1
      && this.zonaloffices[0].zonal_name_eng == "Main Office"
    ){
      this.data.zonaloffice = this.zonaloffices[0].zonal_id;
    }

Anes``