How to dynamically bind the attribute name of an object in an ngFor loop

One scenario I am working on involves assigning an Array of Objects to a select dropdown's options using ngFor like this:

<select>
 <option *ngFor="let item of data" [value]="item.key">{{item.value}}</option>
<select>

Here is my sample data:

[
  {
    "key"   : "CHV",
    "value" : "Chivas"
  },
  {
    "key"   : "BLN",
    "value" : "Balentines"
  },
  {
    "key"   : "BDG",
    "value" : "Black Dog"
  }
]

The goal here is to dynamically bind the properties specified by the user for the option value and label. I attempted the following which did not work as expected:

<option *ngFor="let item of data; let itemlabel = optionlabel; let itemvalue = optionvalue" value="{{item.itemvalue}}">{{item.itemlabel}}</option>

The component includes 'optionvalue' and 'optionlabel' strings defined as follows:

optionvalue : string = 'key';
optionlabel : string = 'value';

By switching these strings, I can interchange key and value for each option. Any suggestions on how to achieve this effectively?

Answer №1

You have the option to employ this code snippet:

<option *ngFor="let item of data" value="{{item[itemvalue]}}">
  {{item[optionlabel]}}
</option>

Utilizing this method allows us to make use of the setup carried out in your component.

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

Redirect to the homepage if the requested page is not found in IIS

Within my IIS Website, there are three applications being hosted. The main website is an Angular App, alongside an API application housing all APIs and another application that is a pure javascript project hosted under the application alias /vmenu/. Any r ...

Tips for incorporating a TypeScript enum value into an Angular2 ngSwitch expression

Is there a way to effectively use Typescript enums with Angular2's ngSwitch directive? I keep encountering the error "Cannot read property 'xxx' of undefined in ..." when attempting to utilize an enum in my component's template. How can ...

Unable to showcase a dynamic image using [style.background-image] in Angular 7

I am encountering an issue in my Angular application where I am unable to load background images dynamically from my backend. Displaying regular pictures is not a problem for me. However, the background images are not loading and I do not receive any err ...

Testing Angular components with Karma Server: An uncaught promise rejection occurred stating, "The code should be executed within the fakeAsync zone."

For my unit test development, I am utilizing karma. In some of my test cases, I have used fakeSync - tick() and promises. Although my tests are running successfully, there seems to be an issue with the karma server: my test.spec.ts : import { async, Co ...

If you try to paste the same value into the Input field a second time, the two-way data binding fails to update

Looking for help with an input tag: <input type="number" [ngModel]="position" (ngModelChange)="onChangePosition($event)" /> The onChangePosition function is set up to trim the input value to 3 numbers if it exceeds that length. For example, when e ...

Issues with expected identifiers and type mismatch errors encountered when defining a TypeScript class

As someone who is still relatively new to coding, I am facing a challenge while trying to create a TypeScript class within an Angular project that is based on a complex JSON file. The issue arises from the way the properties were defined in the JSON using ...

Creating Typescript: Defining the Type of Object Key for a Generic Type

I've created a custom hook with a generic type to define the return type of the hook. Below is an example of the code I wrote for this custom hook: type Return<T> = [T, (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void, ...

Searching for an entity that may contain fetchable connections

Utilizing my REST API allows me the option to fetch relations based on specific requests. For instance, a basic call like GET /payment-request will return the following simplified payload: [ { "id": "01FBPR3K0RYBCRGCBWEC2AK30P", ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

Is there a collation method for MatSort that accommodates languages with alphabetical orders differing from Unicode orders?

When it comes to the Norwegian and Danish Alphabets, the proper order of the characters is as follows: Æ Ø Å However, MatSort follows the Unicode order for these characters: Å (197) Æ (198) Ø (216) Is there a way to implement collation to addre ...

Ways to confirm if a user has previously participated in a poll?

SCENARIO: At present, I am storing an array of objects within the User model to track all the votes cast by the user. Here is a glimpse of the model structure: var schema = new Schema({ firstName: {type: String, required: true}, lastName: {type: ...

Strategies for capturing a module's thrown exception during loading process

Is there a way to validate environment variables and display an error message on the page if the environment is found to be invalid? The config.ts file will throw an exception if the env variable is invalid. import * as yup from 'yup' console. ...

What is the proper way to incorporate ts-nameof in the gulp build process and encounter the error message: 'getCustomTransformers' is a compiler option that is not recognized

Utilizing ts-nameof in my TypeScript files, similar to this example in a .ts file: import 'ts-nameof'; export class MyTsNameOfTest { public testTsNameOf() { const nameString = nameof(console.log); } } My Gulp build task setup - followi ...

I am experiencing issues with my Angular2 project where not all of my component variables are being passed to the

My problem involves sending three variables to my HTML template, but it only recognizes one of them. The HTML template I am using looks like this: <div class="page-data"> <form method="post" action="api/roles/edit/{{role?.ID}}" name="{{role? ...

Modify the JSON file without using a library

I am dealing with a file called test.json Here is what it contains: [ { "data_on": { "vals_e": "", "vals_o": "" }, "data_off": { "vals_d": "" ...

The Angular swiper appears to be malfunctioning as it is not showing any content

I possess a file that contains HTML markup: <div class="reviews__inner"> <swiper [pagination]="{ type: 'fraction'}" [navigation]="true" class="mySwiper"> <div class="sl ...

The Angular2 module is unable to find matching child routes for the component

My web app is built using Angular 2 and has a submodule named tutorial with its own sub-router to navigate through different chapters. Below is the structure of my application: tutorial.module.ts: import { tutorialRouting } from './tutorial.routes&a ...

Mastering Props Typing in React Using TypeScript

Currently, I am faced with the task of defining the following: interface MyCompProps { someAttr: number } Instead of having to explicitly list all the aria-* attributes I need upfront, I would like to simply use aria- and other normal HTML attributes ...

Is there a method to dynamically insert commas into numeric values within an input field using an Angular Reactive Form?

Is there a way to automatically insert commas after every 3 digits as numbers are being typed into the input field? Currently, I am using the (blur) function which adds commas only after clicking away from the input field. However, I would like this proc ...

Establish a connection to postgresql database with typescript from a node.js server

I am a beginner when it comes to TypeScript and Node.js. I am interested in connecting a Node server to a Postgres database within a containerized environment. I have found examples for this using only JavaScript, but I need guidance on how to do it with T ...