The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2).

I'm loading the data in the ionViewWillEnter method and pre-selecting it with NgModel.

Here is the appearance:

Initial load of the page

After opening the select (pre-selected value visible)

HTML code for the select:

    <ion-row>
  <ion-col>
    <ion-item lines="inset">
      <ion-label hidden>Select departments</ion-label>
      <ion-select (ionChange)="loadOpenTicketsForDepts()" style="min-width: 100%"
        placeholder="Select departments..." multiple [(ngModel)]="selectedDepartments" cancelText="Cancel"
        okText="OK">
        <ion-select-option value="{{dept.id}}" *ngFor="let dept of departments">
          {{dept.name}}
        </ion-select-option>
      </ion-select>
    </ion-item>
  </ion-col>
</ion-row>

Typescript data loading:

  ionViewWillEnter(): void {
//1. get department where logged in employee is working
this.authService.getPersNr().then((res) => {
  //now load department
  this.ticketService.getEmployeeByName(res).subscribe(emp => {

    const costcenter = emp.costcentreId;

    this.costCentreService.getDepartmentById(costcenter).subscribe(dept => {
      //add to selected departments if it is not already included
      if (this.selectedDepartments.includes(String(dept.id)) == false) {
        this.selectedDepartments.push(String(dept.id))
      }
      //now load tickets for all selected departments
      this.loadOpenTicketsForDepts();
    })
  })
})

this.costCentreService.getDepartments().subscribe(res => {
  this.departments = res;
})

}

Answer №1

To enhance your code, include a reference to the selector named #departmentSelector:

 <ion-select #departmentSelector (ionChange)="loadOpenTicketsForDepts()" style="min-width: 100%"
    placeholder="Abteilungen wählen..." multiple [(ngModel)]="selectedDepartments" cancelText="Abbruch"
    okText="OK">
    <ion-select-option value="{{dept.id}}" *ngFor="let dept of departments">
      {{dept.name}}
    </ion-select-option>
  </ion-select>

Subsequently, access it in your TypeScript class after the view has loaded:

Declare your reference:

  @ViewChild("departmentSelector") departmentSelector!: IonSelect;

You can then make use of it once the view is completely loaded:

ngAfterViewInit(){


//your async function ...

this.authService.getPersNr().then((res) => {
  //now load dept
  this.ticketService.getEmployeeByName(res).subscribe(emp => {

    const costcenter = emp.costcentreId;

    this.costCentreService.getDepartmentById(costcenter).subscribe(dept => {
      //add to selected departments if it is not already included
      if (this.selectedDepartments.includes(String(dept.id)) == false) {
       // this.selectedDepartments.push(String(dept.id))

this.departmentSelector.value = String(dept.id);
   
   }
      //now load tickets for all selected departments
      this.loadOpenTicketsForDepts();
    })
  })
})


//


}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to mainta ...

Arrange the table by column following a service request

Is there a method to organize the table below once it has been loaded? I am utilizing Google API to retrieve distance matrix data, but I want the table to be sorted by distance. However, this sorting should take place after the Google service call is comp ...

Vuejs allows objects to trigger the execution of methods through elements

My goal is to utilize a function in order to individually set the content of table cells. In this specific scenario, I aim to enclose the status with the <strong> - Tag (I refrain from modifying the template directly because it is stored within a com ...

Error: JSON encountered circular structure when attempting to serialize an object of type 'ClientRequest' with a property 'socket' that references an object of type 'Socket'

Encountering an error while attempting to make a POST request to my TypeORM API using axios: TypeError: Converting circular structure to JSON --> starting at object with constructor 'ClientRequest' | property 'socket' -&g ...

Using AngularJS with the Chosen Plugin to pre-select a value in a dropdown menu

After following the guidance from this URL, I successfully incorporated the chosen plugin into Angular.js. Now that I can retrieve the value, my next objective is to have the selected value be pre-selected in the chosen dropdown menu. If anyone has a sim ...

What is the process for launching a TypeScript VS Code extension from a locally cloned Git repository?

Recently, I made a helpful change by modifying the JavaScript of a VSCode extension that was installed in .vscode/extensions. Following this, I decided to fork and clone the git repo with the intention of creating a pull request. To my surprise, I discove ...

Checkbox and Ionic avatar image combined in a single line

I am currently working on a mobile app using the ionic framework. I would like to create a layout with an avatar image on the left, text in the middle, and a checkbox on the right. Can anyone provide guidance on how to achieve this? The code snippet below ...

Is there a way to deactivate other dropdown options?

To simplify the selection process, I would like to disable the options for "Province", "City", and "Barangay". When the user clicks on the "Region" field, the corresponding "Province" options should be enabled. Then, when a specific province is selected, t ...

Techniques to dynamically insert database entries into my table using ajax

After acquiring the necessary information, I find myself faced with an empty table named categorytable. In order for the code below to function properly, I need to populate records in categoryList. What should I include in categoryList to retrieve data fro ...

Challenges encountered while implementing generic types in TypeScript and React (including context provider, union types, and intersection

I have a fully functional example available at this link: The code is working properly, but TypeScript is showing some errors. Unfortunately, I've run out of ideas on how to make the code type safe. I've searched extensively for examples that ma ...

I am puzzled as to why my code in React is rendering twice without any apparent reason

I ran into a strange issue where my console.log("hi") was being displayed twice. I was working on a simple todo-list project and noticed that everything was getting double clicked. After some troubleshooting, it seems like the code is executing any JavaScr ...

Developing a JSON structure from a series of lists

var data = [ [ "default_PROJECT", "Allow", "Connect", "Allow", "AddComment", "Allow", "Write", "Allow", "ViewComments", "Allow", "ExportData", "Allow", ...

Enhance JSON nesting with knockoutJS

I am currently working on updating a JSON object in memory using the knockout.js user interface. However, I have encountered an issue where changes made in the UI do not seem to reflect on the JSON data itself. To troubleshoot this problem, I have added bu ...

Audio waves visualization - silence is golden

I am attempting to create a volume meter, using the web audio API to create a pulsation effect with a sound file loaded in an <audio> element. The indicator effect is working well with this code; I am able to track volume changes from the playing aud ...

ng-options encounters duplicate data when using group by in Internet Explorer

The dropdown menu that lists states works fine in Google Chrome, but duplicates groups in Internet Explorer. In Chrome, there are 2 groups, but in IE there are 4. How can I fix this issue in IE as well? Thank you. Here is the code snippet: <!DOCTYPE h ...

Verify the presence of a GET parameter in the URL

Working on a simple log in form for my website using Jade and ExpressJS. Everything is functioning correctly, except for one issue - handling incorrect log in details. When users input wrong information, they are redirected back to the log in page with a p ...

I am puzzled as to why my DataGrid MUI component is not functioning properly

I am taking my first steps with MUI, the MaterialUI React Component library. After following the installation instructions in the documentation, I am now attempting to integrate the DataGrid component into my React project. My goal is to replicate the fir ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

Guide to specifying a type as optional based on specific criteria

In coding, there exists a certain type that is defined as follows: type PropsType = { dellSelectedOption: (id: string, idOptions: string[]) => void; ownFilterData: Array<ActiveFilterAndPredFilterDataType>; watchOverflow: boolean; childre ...

Is there a way to connect a Button to a different page in VUE.JS?

I currently have a button that needs to be linked to another page. This is the code I am working with at the moment. How can we write this login functionality in vue.js? It should direct users to the page "/shop/customer/login" <div class="space-x ...