Tips for retrieving both the ID and NAME values from Ionic's Dynamic Select Options

In my Ionic 3 project, I have successfully implemented a dynamic select option. However, I am facing an issue where I can only retrieve either the ID or the Name value of the selected option from the server, but not both.

I have tried using JSON.parse and accessing id.value and name.value in the options, but it seems I am only able to capture the first value. Can someone please help me with this? Here is the code snippet:

 <ion-list >
    <ion-item class="list-but">
      <ion-label>Tipo de Ambiente</ion-label>
      <ion-select
        [(ngModel)]="idType"
        multiple="false"
        cancelText="Cancelar"
        okText="Ok"
      >
        <ion-option
          *ngFor="let type of type_environment"
          [value]="type.id"
          #name
          >{{ type.name }}</ion-option
        >
      </ion-select>
    </ion-item>
  </ion-list>
  <button ion-button block (click)="insert()">Salvar</button>


``public type_environment = new Array<any>();
  public idType: number = 0;
  public nameType: string = "name";
  private userData: any;`

insert() {
    this.userData = this.user.getUserData();

    let body = {
      name: this.nameType,
      id_type: this.idType,
      id_unity: this.navParams.get("id.unidade")
    };
    console.log("name:", this.idType);

    this.route.postData("/ambiente", body).subscribe(
      data => {
        let response = data as any;

        let ret = JSON.parse(response._body);

        if (ret.insertId) {
          this.navCtrl.popToRoot();
        } else {
          console.log(ret);
        }
      },
      error => {
        console.log(error);

Answer №1

Instead of having two value attributes in your select element, simply bind the entire object to value, like this:

<ion-select [(ngModel)]="idType" cancelText="Cancelar" okText="Ok">
  <ion-option *ngFor="let type of type_environment" [value]="type">
    {{ type.name }}
  </ion-option>
</ion-select>

After doing this, the selected object will be stored in idType:

insert() { 
  // Access the id and name properties of the chosen object here
  console.log(this.idType.id, this.idType.name)
}

Check out a DEMO here

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 there a different way to retrieve the tag name of an element besides using

Currently, I am dealing with an outdated version (Chromium 25) of chromium. My goal is to utilize the tagName method in order to retrieve the name of the specific HTML tag being used. While I am aware that Element.tagName functions for versions 43 and ab ...

Experience an issue in your Ionic/Angular app with the `e.gesture` being undefined during Drag & Drop functionality. Additionally, explore the use of two separate Controllers

Currently, I am in the process of developing an application that requires the implementation of Drag & Drop functionality as a primary interaction feature. To provide a clearer picture, envision an Ionic Side Menu containing an <ion-list> displaying ...

Cross-origin and allow-origin headers are configured, yet there is still no response

After setting up my server to return data, I included the following code in my response: header('Access-Control-Allow-Origin: *'); echo 'the response'; When checking the response using Chrome Dev Tools, I can see that "Access-Control- ...

Utilizing TypeScript's discriminated unions for function parameters

The function's second argument type is determined by the string value of the first argument. Here is an example of what I am trying to achieve: async action (name: 'create', args: { table: string, object: StorageObject }): Promise<Sto ...

Instructions on invoking a setter method in Angular

I am looking to implement a setter method to update my form. When should I invoke the setter method? Below is the code snippet from my component.ts: export class UpdateZoneComponent implements OnInit { profileForm: FormGroup products: any; h: number; c ...

Necessitating derived classes to implement methods without making them publicly accessible

I am currently working with the following interface: import * as Bluebird from "bluebird"; import { Article } from '../../Domain/Article/Article'; export interface ITextParsingService { parsedArticle : Article; getText(uri : string) : B ...

Issues with the messaging functionality of socket.io

Utilizing socket.io and socket.io-client, I have set up a chat system for users and operators. The connections are established successfully, but I am encountering strange behavior when it comes to sending messages. For instance, when I send a message from ...

What is the process for displaying objects within an object using HTML?

I'm developing an app using Angular and Node.js. I have a complex data structure where one object (order) contains a list of objects (items), which in turn include another list of objects (product IDs). My goal is to properly display all this data wit ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

ExpressJs Request Params Override Error

I am currently utilizing express version 4.19.2 (the latest available at the time of writing) This is how I have declared the generic type Request interface ParamsDictionary { [key: string]: string; } interface Request< P = core.ParamsDictionary, ...

Encountered an issue locating the stylesheet file 'css/style.css' that is supposed to be linked from the template. This error occurred when trying to integrate Bootstrap with Angular

<link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css"> <link rel="stylesheet" href="plugins/owl-carousel/owl.carousel.css"> <link rel="stylesheet" href="plugins/magnific-pop ...

Navigating through a large array list that contains both arrays and objects in Typescript:

I have an array containing arrays of objects, each with at least 10 properties. My goal is to extract and store only the ids of these objects in the same order. Here is the code I have written for this task: Here is the structure of my data: organisationC ...

Retrieving data using ngxs selector for displaying nested JSON data

My issue is related to the user object that contains nested arrays, making it difficult to access secondary arrays. I have created selectors with ngxs to retrieve and utilize data in HTML code, but extracting secondary arrays seems impossible. { "us ...

Encountering issues with MediaSession.setPositionState() and seekto functionalities not functioning properly

Having trouble with MediaSession.setPositionState() not displaying the audio time and seekbar not behaving as expected. const sound= document.querySelector('sound'); function updatePositionState() { if ('setPositionState' in navigato ...

Alter the color scheme of the material dialog's background

I have been trying to change the background color of a dialog, but so far I have only been successful in changing the outline. I used the panelClass property as I believed it was the correct way to do it. https://stackblitz.com/edit/jm9gob ...

Transforming AngularJS 2.0 code into ES6 syntax

Successfully implemented the AngularJS 2.0 5 Minute Quickstart in my IntelliJ IDEA 14.1.4 following a helpful Stackoverflow Answer on AngularJS 2.0 TypeScript Intellij idea (or webstorm) - ES6 import syntax. However, it seems to focus on compiling TypeScr ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Changing a complex object within a nested array of a BehaviorSubject

I'm currently working on an Angular app. Within my service, DocumentService, I have a BehaviorSubject that holds an array of Documents. documents: BehaviorSubject<Document[]> Let me provide you with some insight into the various classes I' ...

npm ERROR! Encountered an unexpected symbol < within the JSON data at position 12842

I keep encountering an error every time I attempt to install a package or run npm install. Despite my limited experience with Angular 4, having only started using it a week ago, I am puzzled by this error. Any guidance on how to resolve it would be greatly ...