Transitioning an Angular dropdown from static data to dynamic data fetched from a live service

I am facing a challenge with my Angular 5 dropdown. It currently works well with hard coded data, but I now need to switch it to live data. The issue is that the live data I have is in plain array format.

Here is how it currently functions

HTML

<select...
  <option *ngFor="let activityType of activityTypes" [ngValue]="activityType.Id">
        {{activityType.Activity}}
  </option>

Typescript Component

activityTypes: any[];

this.activityTypes = [
        { Id: 1, Activity: "Select One" },
        { Id: 2, Activity: "Insert" },
        { Id: 2, Activity: "Update" },
        { Id: 3, Activity: "Delete" },          
];

However, the challenge arises when I retrieve data from a service and the format is as follows:

this.activityTypes v["INSERT", "UPDATE"]
                      0: "INSERT"
                      1: "UPDATE"

click to see dev tool image output

Now, how can I bind this array to the dropdown? Ideally, I would like to set values as "0" and "1" for the array, and then display "INSERT" and "UPDATE" respectively...

Answer №1

Utilize the array index as the option value and the data as the label

<select...
  <option *ngFor="let activityType of activityTypes; let i = index" [ngValue]="i">
        {{activityType}}
  </option>

Solution2: Generate an array of objects like this:

this.activityTypes = this.activityTypes.map((currElement, index) => {
  let obj = {
    Id: index,
    Activity: currElement
  };
  return obj;
});

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 event 'deviceorientation' does not seem to be firing in iOS browsers when it is referenced within an iFrame

I am currently working on a website that features a "360 panorama viewer" embedded within an iframe. The source page utilizes JavaScript and window.DeviceOrientationEvent to determine if the user is browsing on a mobile device with orientation functionalit ...

Tips for displaying the date in 13-digit Unix Timestamp format using JSpreadSheet

I am faced with a challenge involving data that is stored in Unix Timestamp format, which I need to display as a readable date (e.g. YYYY/MM/DD) in JSpreadSheet ("jspreadsheet-ce"). Currently, the data appears as a 13-digit number and looks unattractive. ...

Determining a segment of a constant object's type

Suppose I have a function that requires a specific interface interface Foo { foo: number; bar: number; baz?: number; buz?: number; } const doFoo = (params: Foo) => { /* ... */ }; I also possess a constant containing default values for some pro ...

Basic stack-driven device programmed in C

I'm tasked with developing a basic stack-based machine. This machine's instruction set includes 5 operations: push, pop, add, mult, and end. I need to handle a source code file containing an instruction section (.text) as well as a data section ( ...

What steps are involved in uploading data to serve as a filter while running a PHP script to retrieve data from an SQL database?

Currently, I am retrieving data from a PHP file using miniAjax. The code snippet below demonstrates how the process begins: microAjax("genjsonphp.php", function(data) { var json = JSON.parse(data); var points = json; //code continues In the c ...

Exploring the world of unit testing in a store - any tips on getting it to work

I am currently working on a store.js file import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const mutations = { increment: state => state.count++, Changeloading(state, status) { state.loading = status }, Cha ...

Is there a way to differentiate the color of an active link from an inactive one, so users can easily identify which link they are currently viewing?

How can I customize the color of text for the active page on my website's sidebar? For example, I have two hyperlinks, one for HOME and one for ABOUT. When a user clicks on the HOME link, I want the text color to change to green while the ABOUT link r ...

Utilizing the ternary operator in React and Typescript to show text in place of using extensive if-else statements

I have the following code snippet: notify({ title: `${ filteredIds.length > 0 ? (type === "type1" ? 'type1 checks' : 'type2 checks') + ' started.' : (type === "type1" ? 'type1 checks ...

My goal is to eliminate unnecessary code and transfer it into its own jQuery function

Currently, I am working on optimizing my code by removing redundancies and moving sections to separate functions. //Consolidating Infotypes for filtering and checking if any option is selected if(this.$infoOptions.val() != null){ ...

Exploring ways to access a nested JSON object | Showing Orders in a Laravel E-commerce Platform

{"**6732987ae9ac9ac3d465ea993bf9425c**": {"rowId":"6732987ae9ac9ac3d465ea993bf9425c","id":14,"name":"Stanley Metz","qty":2,"price":2039,"weight":550,"options&quo ...

Table sorting feature with checkboxes has disappeared from view

This segment of code includes HTML for a table along with JavaScript functionality. When a checkbox is clicked, another table will be displayed: <form class="filter"> <input type="checkbox" id="checkboxID" class="unchecked"> EG <input type= ...

Dimension of the element that has been positioned absolutely

One of my challenges involves working with an absolutely positioned div element (.tooltip) containing another div (.text) that has text with a set max-width. The issue arises when the left property of .tooltip is too large, causing its width to shrink du ...

The method getSheetByName() in google script may return null

I'm having trouble setting the sheet title to match the name of the form I've connected with this code. Despite confirming that the sheet's name is "Form Responses 1", the code keeps returning "null". Any advice? var data = SpreadsheetApp.c ...

Angular 5: experiencing issues with HttpClient when using REST API

Currently, I am in the process of developing a REST API using Spring to perform CRUD operations based on a tutorial I found. However, I have encountered an issue with the HTTP client not retrieving data, and upon inspection, I discovered the following erro ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

Return an array that has been filtered to exclude any elements that are also found in a separate array

I have an API that provides a list of cars. const getAsset = async () => dbApi('list_cars', ['', 100]) .then(result => result.map(e => e.symbol)); Here, the function getAsset returns the car list. 0: "BMW" 1: "HONDA" 2: " ...

Whenever I relocate the button's position within the Bootstrap framework, it seems to end up in a completely different

body <div class="container" style="margin-top: 70px;"> <div class="formlogin bg-light bg-gradient shadow-lg p-3 mb-5 bg-body rounded col-8"> <p id="signText"> Signin Fo ...

JavaScript allows for accessing form values easily

I am facing an issue with retrieving form values using JavaScript. Below is the HTML code for the form: <form action="./ExampleServlet" method="POST" id="myform"> <label>Username</label> <input type="text" name="user">< ...

React is encountering a problem with loading the image source and it is

<img src="play.jpg" alt="play"></img> This code works fine in standard HTML, but I'm having trouble getting it to work in React. Is adding it as a background the only solution? ...

"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list wit ...