Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with data from this API?

 TestArrList:any[]=[];
 data1!:any[];
 
 
  ngOnInit(): void {

    let uri = 'APIURL';
    this.http.get(uri).subscribe((data:any) => {  
      this.TestArrList = data
   
for(var i = 0;i < this.TestArrList.length;i++)
       
   for(var j = 0;j < this.TestArrList[i].Items.length;j++)
      this.data1.push(this.TestArrList[i].Items[j].Name);
    console.log(this.TestArrList);
   return this.data1
      

     }); 
     }
 
 
<mat-grid-tile [colspan]="fieldColspan">
              <mat-form-field class="form-field" appearance="outline" style="width:20vw">
                <mat-label>Location </mat-label>
                <mat-select placeholder ="Select test"  [formControl]="testControl">
                  <mat-option *ngFor="let item of TestArrList"  [value]="item.name">
                    {{item.value}}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </mat-grid-tile>

I need assistance in fetching the "Value" (value1 for test, value2 for test, value3 for test) from each Items in the API response.

[
    {
        "Items": [
            {
                "Name": "Id",
                "Value": "1"
            },
            {
                "Name": "test",
                "Value": "value1 for test"
            }
        ],
        "Value": null
    },
    {
        "Items": [
            {

                "Name": "Id",
                "Value": "2"
            },      
            {

                "Name": "test",
                "Value": "value2 for test"
            }
        ],
        "Value": null
    },
    {
        "Items": [
            {
                "Name": "Id",
                "Value": "3"
            },
       
            {
                "Name": "test",
                "Value": "value3 for test"
            }
        ],
        "Value": null
    }
]

Answer №1

You have assigned `data` to `TestArrList`, however, `data` is not in the correct format. You may want to consider using the `reduce` method instead.

TestArrList: any[] = [];
data1!: any[];

ngOnInit(): void {

    let uri = 'APIURL';
    this.http.get(uri).subscribe((data: any) => {
        this.TestArrList = data.reduce((acc, curr) => {
          acc.push(...curr.Items) // destructuring array
          return acc;
        }, []);

      }
    }
<mat-grid-tile [colspan]="fieldColspan">
  <mat-form-field class="form-field" appearance="outline" style="width:20vw">
    <mat-label>Location </mat-label>
    <mat-select placeholder="Select test" [formControl]="testControl">
      <mat-option *ngFor="let item of TestArrList" [value]="item.name">
        {{item.value}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</mat-grid-tile>

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

How to use JavaScript regular expressions to extract the content following the second-to-last occurrence of a back

I currently have a regular expression that looks like this: /^.*[\\\/]/ At the moment, it removes every single backslash from a string. However, now I need to modify it in order to capture everything after the second to last backslash. Fo ...

combination of Electron, Node.js, and Angular

Can I integrate Angular 5 into an Electron project and have Node.js run on the server side as well? While I understand Electron allows for desktop applications, I am curious if it can also support server-side applications. Additionally, I am unsure if it ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

What are some methods to make sure that functions in AngularJS do not run at the same time

I am new to the world of JavaScript and I have encountered a problem with one of my functions. The function is designed to retrieve cached resources, but if the resource is not found in the cache, it makes a call to the back-end. The issue arises when thi ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

Discovering the precise query parameters from a URL within an Angular application

I came across a Stack Overflow post about obtaining query params. However, I noticed that one of my query params contains "%2" which converts to a "+" when displayed in my Angular code. Additionally, my param2 does not store the complete value "testingsome ...

Issue: Unable to load the file named 'script.ts' while employing chrome.scripting.executeScript

Currently, I am working on developing a chrome extension using Vite with React and Typescript along with CRXJS. This is my initial project in this domain. The issue I am encountering is related to executing a script on the current tab when a button is clic ...

Expanding upon passing arguments in JavaScript

function NewModel(client, collection) { this.client = client; this.collection = collection; }; NewModel.prototype = { constructor: NewModel, connectClient: function(callback) { this.client.open(callback); }, getSpecificCollection: ...

Modify the background color of a div by selecting a hex code from a dropdown menu

Is there a way to utilize jQuery in order to alter the background of a <div> by choosing the HEX code from a separate dropdown menu? HTML <select id="target"> <option value="#c2c2c2">Grey</option> <option value="blue">Bl ...

NPM: Handling multiple prehooks with the same name

Is it possible to have multiple prehooks with the same name in my package.json file? For example, having two instances of pretest: "scripts": { "start": "react-scripts start", ... "pretest": "eslin ...

404 Response Generated by Express Routes

Exploring the MEAN stack has been a great way for me to expand my knowledge of node and express. Currently, I am working on creating a simple link between two static pages within the app. My routes are set up as follows: //Home route var index = require( ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

What is the overlay feature in Material-UI dialogs?

I recently started using the React-Redux Material-UI package found at http://www.material-ui.com/#/components/dialog My goal is to implement a grey overlay that blankets the entire dialog element, complete with a circular loading indicator after the user ...

"Use jQuery to select all the cells in a row except for the

I found a visually appealing table layout that looks like this : https://i.stack.imgur.com/oRxYP.png What caught my attention is how clicking on a row selects the entire row. Take the example in the image above, where the second row is highlighted upon s ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...

What is the best approach for addressing null values within my sorting function?

I created a React table with sortable headers for ascending and descending values. It works by converting string values to numbers for sorting. However, my numeric(x) function encounters an issue when it comes across a null value in my dataset. This is th ...

Using jQuery to select all child elements based on a specified condition

Is there a way to locate all instances of .post-comment-replies that have a nested '.post-comment-reply' within them, rather than being at the first level? Currently, the code provided retrieves not only those .post-comment-replies with nested . ...

Video background in webflow not currently randomizing

I want to add a dynamic video background to my website created with Webflow. I attempted to achieve this using Javascript by including the following links: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70fed ...

Currently, I am creating a regular expression to manage a specific task, but I have hit a roadblock in

Criteria: The string must not contain any uppercase letters. Special characters such as '^$.?*+()' are not allowed in the string. If the string includes '[', it must be followed by zero or more characters other than '[' and & ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...