Using Angular: A guide to setting individual values for select dropdowns with form controls

I am working on a project that involves organizing food items into categories. Each item has a corresponding table entry, with a field indicating which category it belongs to. The category is represented by a Guid but displayed in a user-friendly format. Currently, every dropdown menu is part of a new form instance, causing issues with setting values separately as they all use the same form control name.

Below is a snippet of my code:

    <tr *ngFor="let food of foodItems" id="{{food.Guid}}" class="alternate-row">
      <td><label>{{food.foodName}}</label></td>
      <td><label>{{food.foodDescription}}</label></td>
      <td>
        <form class="table_form" [formGroup]="tableForm" (ngSubmit)="onTableFormSubmit(tableForm.value)">
          <select class="form-control" formControlName="foodCategorySelect" (change)="onTableFormSubmit(tableForm.value, food.Guid)">
            <option *ngFor="let foodCategory of foodCategoryList" [value]="foodCategory.Guid" [selected]="foodCategory.Guid == food.category">
              {{ foodCategory.categoryName }}
            </option>
          </select>    
        </form> 
      </td>
    </tr>

Here is some example data from my log:

    foodCategoryList
    0: 
    Guid: "b6b64fba-1879-44fb-8a8d-1b26c2229367"
    categoryName: "Starter"
    [[Prototype]]: Object
    1: 
    Guid: "ba9e3828-ddf0-4db4-bff2-2ec668d973d0"
    categoryName: "Dessert"
    [[Prototype]]: Object

    foodList
    0: 
    foodName: "Chicken Wings"
    Guid: "ec34ce1f-5274-4d32-a17f-4a518fef9a1f"
    foodDescription: "Delicious spicy chicken wings served with sauce"
    category: "b6b64fba-1879-44fb-8a8d-1b26c2229367" --starter
    [[Prototype]]: Object

I'm struggling to figure out how to set values individually. Any help would be greatly appreciated!

Answer №1

If you are looking to create a form for each row, my suggestion would be to utilize template forms for simplicity.

<!-- You do not need a <form> element -->
<select [(ngModel)]="food.category"  <!-- bind the category-->
(ngModelchange)="onTableFormSubmit(food.category, food.Guid)"> <!-- trigger update when it changes -->
...

This should work effectively as is.

Alternatively, if you prefer using the reactive forms API, you would need to create a reactive form instance for each row and then incorporate the form into the model.

foodItemsTableData = this.foodItems.map(food => ({
  ...food,
  categoryControl: 
}))

This method may seem a bit cumbersome, but the binding would simply be

[formControl]="food.categoryControl"

Another option is to establish indexes dependency.

// ts
foodCategoriesControls = this.foodItems.map(food => new FormControl(food.category));
// updates subscriptions can be in typescript file in this case
...
// html
<tr *ngFor="let food of foodItems; index as i"
<select [formControl]="foodCategoriesControls[i]" (change)="onTableFormSubmit(foodCategoriesControls[i].value, food.value)"

You could also nest the category controls within forms, similar to your previous example, although it may not be necessary.

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

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

Increase the Step Size of an HTML Number Input by Holding Down the Time

Is there a way to implement increasing increment/step size for number inputs in HTML based on how long the user holds the stepper arrows? For instance, starting at step size=1 and gradually ramping up to larger increments like 5, 10, 20, etc. after holdin ...

The package import path varies between dynamic code generation and static code generation

I have organized the src directory of my project in the following structure: . ├── config.ts ├── protos │ ├── index.proto │ ├── index.ts │ ├── share │ │ ├── topic.proto │ │ ├── topic_pb. ...

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

A beginner's guide to using Jasmine to test $http requests in AngularJS

I'm struggling with testing the data received from an $http request in my controller as I don't have much experience with Angular. Whenever I try to access $scope, it always comes back as undefined. Additionally, fetching the data from the test ...

Steps for releasing a third-party library that is compatible with both Angular 2 and Angular 4

Currently, I am utilizing a third-party library for Angular that is compatible with Angular 2. However, I want to make sure this library can support all versions of Angular, including Angular 4 and Angular 5. How can I go about publishing an updated vers ...

Using Sequelize to Link Two Columns Between Tables

In my sequelize database, I have the following table settings: const Accounts = sequelize.define('Accounts', { name: DataTypes.STRING, }); const Transfers = sequelize.define('Transfers', { value: { type: DataTypes.DECIMAL(10, ...

The jQuery click event is failing on the second attempt

My PHP code dynamically generates a list, and I want to be able to delete rows by clicking on them. The code works fine the first time, but not the second time. HTML <li> <div class="pers-left-container"> <img src="<?php ech ...

The Angular Proxy seems to handle GET requests successfully, but encounters issues when it comes to

After setting up a proxy for my requests on my Angular application, I successfully managed to redirect my GET request to http://localhost:3000/api/users. However, the issue arises with my POST request as it continues to go to http://localhost:4200/api/user ...

What strategies can be employed to manage three conflicting versions of a single library within a Vite project?

I am currently facing a unique challenge in my web app development process. Specifically, I am using the Vite framework with the svelte-ts template setup to build an application that integrates different libraries for WebXR based augmented reality. The goa ...

Making the Select Tag function as an on-click event in JQuery

So I currently have a tab set up that functions as on click links when viewed on desktop. However, for tablet and mobile devices, I need it to be transformed into a select drop down list while maintaining the same functionality. Below is the code used for ...

Control the start and stop of an Express.js app in Node.js using PHP

I'm currently developing a web service using express.js in the node.js npm environment. In order to deliver this project to my client, I need to create a controller file that allows me to start and stop the server without having to use the command pr ...

Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button> There is also JavaScript code involved: toCSV: func ...

Tips for Safely Utilizing localStorage in Angular

When dealing with easily changeable localStorage data, how can access controls and security be improved in an Angular App? Imagine if our localStorage contains: data - {name:user, account_status:inactive,...} It is concerning that a user could effortl ...

Tips for updating content (wishlist) without the need to refresh the page

Currently experimenting with the TMDb API to enhance my PHP skills. I've successfully created a wishlist feature and now looking to optimize the script. A function is implemented on each movie page for adding movies to the wishlist. function getButt ...

Steps to store a string with all characters in a JavaScript variable

I am faced with a situation where I need to pass variables that are considered Javascript objects, in a format similar to the following: var pageVars= [ { origin:'page', property:'name', value:'whatever' }, { origin:& ...

Unlocking Extended Functionality in JQuery Plugins

At the moment, I am utilizing a JQuery Plugin known as Raty, among others. This particular plugin typically operates as follows: (function($){ $.fn.raty = function(settings, url){ // Default operations // Functions ...

retrieve asynchronous data from the server using ngrx

How can I retrieve asynchronous data from the server? I am looking to save this data in a global store for future updates. I'm having trouble grasping the concept of asynchronous calls, such as in Redux. While I was able to understand it with simpl ...

Is there a method to extract the y value for a specific x value that is not part of the current data set in a Chart.js graph

I have a set of data points like { x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }. With Chart.js, I can easily create a chart based on these points. Is there a method to retrieve the y value for a specific x value, such as 13, from the rendered chart? ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...