What is the best way to exhibit information from a get request within an option tag?

My GET request is fetching data from a REST API, and this is the response I receive:

{
    "listCustomFields": [
        {
            "configurationType": null,
            "errorDetails": null,
            "fieldId": "312329",
            "listItems": [
                "Banking Services",
                "Business Banking",
                "Commercial",
                "Consumer Lending"
            ],
            "name": "Department Name",
            "required": "true",
            "show": "true",
            "value": null
        },
        {
            "configurationType": null,
            "errorDetails": null,
            "fieldId": "373914",
            "listItems": [
                "BB Account Servicing - Add/delete signer",
                "BB Account Servicing - Online Banking for Business - Add Business Account Form",
                "BB Lending - Express Business Credit Application"
            ],
            "name": "Documents being sent",
            "required": "false",
            "show": "true",
            "value": null
        }
    ],
    // more nested JSON objects here...
}

When I try to display the listItems object within the listCustomFields Array in an option tag, the whole list appears on one line.

image description

This is my API call:

  getCustomFields(): Observable<any> {     return this.http.get(this.apiUrl);   }

This is my method:

 getCustomField(){     this.customFieldService.getCustomFields().subscribe((res) => {       this.data = res;       console.log(this.data);     });   }

And here is the relevant HTML snippet:

                        <select id="dropdown" name="listCustomFields" class="form-select" formControlName="listCustomFields" >
              <option *ngFor="let d of data.listCustomFields; let index = index;"><ng-container  *ngIf="index===0">{{ d.listItems }}</ng-container>
              </option>
            </select>

I'm facing some issues with the formatting. Any guidance would be highly appreciated.

Answer №1

Unfortunately, I don't have much time to go into more detail, but it's important to remember that 'listItems' is actually an array. To access a specific item in the array, you will need to use an index like 'd.listItems[0]' which would display "Banking Services". If you just reference 'd.listItems', you will see all the entries within the array.

I suggest using another *ngFor loop by iterating over 'listItems' with {{x}} as one of the values.

In addition, your implementation of ng-container seems a bit unconventional. Here is an alternative way to write this code snippet:

<ng-container *ngFor="let d of data.listCustomFields; let index = index;">
     <option *ngFor="let x of d.listItems">{{x}}</option>
</ng-container>

Answer №2

When making a GET request, it is recommended to use pipe, catchError, and throwError. Also, make sure to handle successful and unsuccessful responses separately in your subscribe method by using next and error or 'complete'. Check out this link for more information: https://rxjs.dev/deprecations/subscribe-arguments.

In the updated version of James' code, remove any unnecessary indexes like so:

<ng-container *ngFor="let d of data.listCustomFields">
     <option *ngFor="let x of d.listItems">{{x}}</option>
</ng-container>

Avoid declaring variables that are not needed. Have a fantastic day! ╰(°▽°)╯

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 error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

breaking down ajax json responses

I am attempting to extract specific data from a JSON response provided by a web service using the code below. function getADData() { var strSearch = $('#txtSearch').val() var ajaxData = "{ 'PartNameString': &apo ...

Hear the Network Transformation - Ionic 2

Monitoring network changes and taking action in my Ionic 2 Mobile application has been a challenge. I have utilized the network module of Ionic for this purpose. $ ionic cordova plugin add cordova-plugin-network-information $ npm install --save @ionic-nat ...

What is the best way to determine the remaining time until a cookie expires in seconds?

I recently set a cookie with an expiration time of 2 minutes. Now, I am looking for a way to display a countdown in HTML showing the seconds remaining before that specific cookie expires using Angular 2. ...

Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format): [ { "name": "john", "lastName": "doe", "gender": "male" }, { "name": &qu ...

Creating a Rails model without an associated HTML view involves generating the model using Rails scaffolding

Is there a way to ensure that my model always returns JSON, regardless of conneg or file-like extensions in the URI such as /app/model.json? I have tried searching online without much success, but I'm sure there must be a simple solution. ...

Create an interface that inherits from another in MUI

My custom interface for designing themes includes various properties such as colors, border radius, navbar settings, and typography styles. interface ThemeBase { colors: { [key: string]: Color; }; borderRadius: { base: string; mobile: st ...

Extract the value of a key from a JSON object

Can anyone help with this JavaScript code? I'm trying to add the values from the "avg" key to an array called labels. However, when running the code, I'm getting undefined values in the array. labels: string[] = []; dataSets: number[] = []; j ...

Convert the PHP variable into a JSON object

i am currently working on a project with Codeigniter below is my PHP switch-case section case 'check': $balance = $this->Model_transactions->getUserBalance($this->input->post('userId')); $needToPay = floatval($this->inp ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

How to assign a value to a component variable using props in Vue.js

I am attempting to assign a props value to my component variable. Below is the code I'm working with: export default { props: { // eslint-disable-next-line vue/require-default-prop multiPaginatedTableTitle: { type: Stri ...

Encountering a Next.js event type issue within an arrow function

After creating my handleChange() function to handle events from my input, I encountered an error that I'm unsure how to resolve. Shown below is a screenshot of the issue: https://i.sstatic.net/fWJA2.png I am currently working with Next.js. In React ...

Getting the first nested object within an object in Angular 8: A comprehensive guide

Looking to extract the first object from a JSON data set? In this case, we want to retrieve {"test": {"id":1, "name":"cat"}} from the following object: { "3": {"test": {"id":1, "name":"cat"}}, "4": {"test": {"id":2, "name":"dog"}}}. Keep in mind that the ...

Error: Index out of bounds for Java array

I encountered a problem and received the following error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at JavaProject.main(JavaProject.java:70) Below is the code snippet where the issue occurred: try { PrintWr ...

Obtain the input value from a modal and receive an empty string if no value

Utilizing ng-multiselect-dropdown within my bootstrap modal allows users to choose multiple products. Each time an item is selected (onItemSelect), a new div is inserted using the jQuery method insertAfter(). This new div displays the quantity of the selec ...

Program designed to eliminate any c-style comments found within a JSON file

Imagine having a json file with c style comments /* ... */ added for readability purposes, like this: { "filename" : "alice " , /* name of the file */ /** assume this case never happens "filename" : "alice /*bob*/" **/ /*** some comments */ ...

typescript optimizing initial load time

When importing the npm package typescript, it typically takes around 0.3 seconds. Is this considered an acceptable load time? Are there any steps that can be taken to optimize performance? The code snippet in index.js demonstrates the process: import &apo ...

I've been encountering an issue with the WebClient.DownLoadString function where it inserts """ in front of each element of my JSON data. Is there a way to properly parse the

In my MVC application, I am facing an issue while trying to access a REST Service. I am using the getJSON method to retrieve data from a controller, which internally calls the REST service and returns data in JSON format. However, when executing the Downlo ...

leveraging jQuery mobile for asynchronous requests

I've been attempting to print a jQuery mobile element using ajax, but I'm running into an issue where the result isn't being encoded as jQuery mobile is intended to do. Below is a simplified excerpt of the JavaScript code responsible for t ...

A step-by-step guide on converting a CSV file to JSON using Python, with the headers of the CSV file becoming keys for each JSON value

I need help with a specific use case. Can someone create a function called “myfunccsvtojson” that can take in the file path of a CSV file (please refer to the attached CSV file) and produce a file containing streamable line delimited JSON? • The ...