Unable to extract numerical value from object using Dropdown (Angular 4)

When I retrieve data from an API, everything works smoothly except when I try to bind my JSON option number value into the [value] tag. Here's an example:

SUCCESSFUL (data retrieved from API is selected in the option)

<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.name">{{ c.name }}</option>
</select> <!-- select with c.name on value -->

UNSUCCESSFUL (data not selected and first option is null)

<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.value">{{ c.name }}</option>
</select> <!-- select with c.value on value -->

JSON object:

subdimension = [{'name': 'sub1','value': 2},
{'name': 'sub2', 'value': 4},
{'name': 'sub3', 'value': 8}]

My goal is to bind a number value into some selects and then sum them all together like:

data.from.api.one + data.from.api.two...

UPDATE:

Here is the component code for the data.from.api:

constructor(public dataService: DataService) {
    this.dataService.getData().subscribe(data => {
      this.datas = data;
    });
  }

getData() {
return this.http.get('https://api.url/').map(response => response.json());
}

datas: Data[];

data = {
  from: { api: { one: '', two: '', three: '' } }
}

Answer №1

All systems are functioning correctly. I have successfully set up a Plunker. Remember to assign the ngModel value after making the request.

<select [(ngModel)]="data.from.api.one" class="form-control">
 <option *ngFor="let c of subdimension; let i = index" [ngValue]="c">{{ 
   c.name }}</option>
 </select>

If you prefer a strictly numerical output

<select [(ngModel)]="data.from.api.one" class="form-control">
 <option *ngFor="let c of subdimension; let i = index" [value]="c.value">{{ 
   c.name }}</option>
 </select>

To implement this code in your Angular component, utilize the ngOnInit hook

return this.http.get('https://api.url/').map(res => res.json()).do((d) => {

     this.subdimension = d;
        //if using an object
        this.data.from.api.one = d[0]
        //if using a value
        this.data.from.api.one1 = d[0].value
     })

Alternatively,

 this.dataService.getData().subscribe(datas => {
  this.datas = datas;
   this.data.from.api.one = datas[0]
        //if using a value
        this.data.from.api.one1 = datas[0].value
});

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

Setting up AngularJS can be a pain

Greetings, my name is Rahim. While setting up AngularCLI, I ran into the following issue: 'ng' is not recognized as an internal or external command, operable program or batch file. C:\Users\ASUS ROG>ng --version 'ng' is ...

"Unraveling the Mystery: Leveraging jQuery to Unleash the

I'm working on a script that looks like this: $(document).on("click", ".passingID", function () { var ids = $(this).attr('data-id'); $("#idkl").val( ids ); $.ajax({ method: "POST", url: ...

Angular confirmation page following successful HTTP POST request to Web API

First question here... I have been given the task of improving an Angular application, even though I am starting with zero experience in Angular. While I do have some background in JavaScript, I mostly work with Java (JSP's and yes, JavaScript). Despi ...

What is the best way to eliminate quotation marks surrounding a boolean value within a JSON string?

The current string is: String example = {"test":"true"} However, I would like it to be in this format: example = {"test":true} Is there a way to convert the initial string to match the desired format? ...

Leveraging --expose-gc for TypeScript when working with ts-node or tsx

It appears that neither ts-node nor tsx has support for the --expose-gc flag, leading to the garbage collector object global.gc being undefined. What is the recommended way to handle memory cleanup in TypeScript? ...

Using Jackson to extract array objects from a JSON array without keys and parsing them

My current challenge involves parsing a JSON array that includes an inner list of arrays without any keys. The issue arises when I attempt to deserialize the JSON array as it throws an exception during runtime: com.fasterxml.jackson.databind.JsonMappingEx ...

Iterating through each ID in a table/cell using .NET MVC with the @

Whenever the table is loaded, I need to run a JavaScript function on each row for cell 4. This function will format the JSON string that is inserted into it. The current code I have only updates the first row/cell... I believe the issue may be related to ...

Change the range into a JSON array

How can I create a custom function in Excel VBA to convert a range into a JSON array? Currently, I only have the function signature: Function to_json(input As Range) End Function I need the input to be converted into a JSON array with the following stru ...

Issue with Angular 10 Web Worker: Unable to locate the main TypeScript configuration file 'tsconfig.base.json'

Every time I attempt to run: ng g web-worker canvas I consistently encounter the error message: Cannot find base TypeScript configuration file 'tsconfig.base.json'. After thorough examination of my files, it appears that I am indeed missing a ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

Benchmarking JSON serialization performance in Java APIs

Seeking a benchmark for various serialization APIs, but all the information I've come across is outdated. Does anyone have a link to a current benchmark that they can share? Reminder: not interested in recommendations for specific APIs or personal op ...

Using jQuery to save PHP form output into an Excel spreadsheet

I have a PHP-enabled form on my website for collecting Address details. Currently, the output is sent to my email inbox. However, I would like the output data to be saved in an external Excel file named "address.xls" using jQuery/JSON. The input fields of ...

Extracting array elements from JSON using PHP

In this project, I am analyzing the JSON data available at this link: My main goal is to extract the information from the tags[{"name":""}] section. Specifically, I am interested in retrieving the 'container' value from '"name":"Container"& ...

Is converting the inputs into a list not effectively capturing the checkbox values?

On my website, I have a div that contains multiple questions, each with two input fields. When a button is clicked, it triggers a JavaScript function to add the input values to a list. This list is then intended to be passed to a Django view for further pr ...

Ensuring the Presence of a Legitimate Instance in NestJS

I have been working on validating my request with the Product entity DTO. Everything seems to be in order, except for the 'From' and 'To' fields. The validation works correctly for the Customer and Type fields, but when incorrect data i ...

Mastering the Art of Ag-Grid Integration in Angular 11

Can the Ag-Grid enterprise or community version be utilized with Angular 11? I am currently working with Angular 11 in my application, but have been unable to find any information confirming that AG-GRID supports this version. ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

c# JavaScriptConverter - understanding the deserialization of custom properties

I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object. For example: public class ContentItemViewModel { public string CssClass { get; set; } public MyCustomClass PropertyB { get; set; } } Th ...

The text editor within the NG nickname terminal

After purchasing a new Windows computer, I encountered an issue while attempting to install Angular. The ng commands were not functioning as expected and instead opened a file in the editor. Upon researching a solution at this source, it was suggested tha ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...