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

The animation function in A-frame causes entities to vanish when used with D3.js

Working with the animation property in D3.js has been a bit of a challenge for me. When I include the a-animation directly in the HTML section, everything works as expected. <a-box id="box" position="0 1 0" rotation="0 0 0" scale="1 1 1" color="#4CC3D9 ...

Is there a way to prevent vertical scrolling during left swipes in Ionic?

I am in the process of creating an Ionic mobile application, where the main view consists of a vertical list of cards. I would like each card to be "swipable" in a similar fashion to Google Now cards. I have begun implementing this functionality: $scope. ...

Error: The system encountered an issue while trying to access an undefined property 'find'

I've been working on developing the backend for a wishlist feature, but I've encountered an issue with my code. (node:19677) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined Despite trying to redefi ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

How to fix the error: ui-switch is not a recognized element in Angular 5?

Currently, I am attempting to utilize the ui-switch feature mentioned in this link. However, I have encountered an error: ng : ui-switch is not a known element ng : if ui-switch is An angular component then verify it's a part of this module ...

Developing a Monitoring-Frontend Application with backbone.js

I am in the process of developing a tool for monitoring and analyzing statistics. The current setup is as follows: Collector-Backend: This component receives queries in JSON format from the frontend, fetches and stores them in a cache, and then notifies ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...

Attempting to coordinate a virtual meeting through the utilization of the Zoom API

I'm currently in the process of developing a website using Node.js, Express.js, and Mongodb. One feature I am working on is the ability for users to schedule Zoom meetings directly within the website. The desired functionality would be for users to sc ...

Exploring the process of sending various variables from PHP to a jQuery function

I have a jQuery function that prints charts using the jqPlot framework. I need to print multiple charts with different options, so I have to call this function several times with varying values. My current approach is not very elegant: //----- index.php: ...

Learning to implement the ng2-chart.js directive within Angular 2

I recently installed ng2-charts through npm First, I ran npm install ng2-charts --save and npm install chart.js --save After that, I included the following code in my index.html file: <script src="node_modules/chart.js/src/chart.js"></script> ...

Deployment error on Google App Engine for Angular Universal 13 and Angularfire 7

Upgrading my app from Angular 12 to Angular 13 has caused deployment issues on Google App Engine. The error message reads: ERROR: (gcloud.app.deploy) Error Response: [9] An internal error occurred while processing task /app-engine-flex/flex_await_healthy/ ...

Transition from tslint to a new linter

Is it possible to remove tslint globally and switch to using eslint as the default in my Angular projects? When creating a new project with the command ng new myProj, I would like to have an eslint.json file instead of tslint.json. ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

Enabling auto-expansion for textareas with every keystroke

Currently, I have implemented the following script: jQuery.each(jQuery('textarea[data-autoresize]'), function() { var offset = this.offsetHeight - this.clientHeight; var resizeTextarea = function(el) { jQuery(el).css('h ...

How do I condense nested keys in TypeScript?

If I have two types defined in TypeScript: interface Foo { bar: string; } interface Baz { foo: Foo; } Is it possible to flatten the Baz type in TypeScript (e.g. type FlatBaz = Flatten<Baz>), so that the signature appears similar to this? inte ...

Storing content from external files in Angular 1.x templateCache

I am currently utilizing the Angular templateCache, following the example set in Angular's documentation. var myApp = angular.module('myApp', []); myApp.run(function($templateCache) { $templateCache.put('templateId.html', ' ...

Navigating with the router on a different page

My appcomponent contains all the routes, and on the next page I have several links that are supposed to route to the same router outlet. How can I navigate when a link is clicked? I attempted using [routerLink]="['PersonInvolved']", but I encoun ...

In the world of Knockout JS, forget about using e.stopPropagation() because it won't

In my table, I have two actions that can be performed: Click event on the row level and click while checking a checkbox inside that row. However, when the checkbox is checked, I do not want the click event on the row to be triggered. <tbody data-bin ...

Turn off automatic vertical scrolling when refreshing thumbnails with scrollIntoView()

My Image Gallery Slider has a feature that uses ScrollIntoView() for its thumbnails, but whenever I scroll up or down the page and a new thumbnail is selected, it brings the entire page back to the location of that thumbnail. Is there a way to turn off t ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...