Gather information specifically from a column in an Angular table

I am currently working on a table that dynamically populates its rows using an array. Each row in the 'Value' column contains an input field for inserting data. My question is, how can I collect all the data from the 'Value' column after the user has inputted data? Is it possible to use 'formGroup', or is there a similar alternative method available? It's important to note that the number of rows in the table varies depending on the size of the array. Any guidance on this matter would be greatly appreciated. Thank you.

https://i.sstatic.net/AKwZR.png

Component.ts File

export class AppComponent {
 members = [
   {
     dataLimit: 'Package 1: Voice',
     value: 0,
     uom: 'Minutes',
   },
   {
     dataLimit: 'Package 2: SMS',
     value: 0,
     uom: 'Units',
   },
 ];
}

HTML File

<div>
  <table>
    <thead>
      <tr>
        <th></th>
        <th>Value</th>
        <th>Unit of Measure</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let member of members">
        <td>{{ member.dataLimit }}</td>
        <td><input type="text" value="{{ member.value }}" /></td>
        <td>{{ member.uom }}</td>
      </tr>
    </tbody>
  </table>
</div>

Answer №1

Great job! I have implemented the code as you suggested, and it is working flawlessly. You can check it out and run some tests on it by visiting STACKBLITZ.

Using a FormGroup with an Angular ReactiveForm is indeed the way to go:

  1. Make sure to import the ReactiveFormsModule in your module (such as AppModule) where you want to use the form (like AppComponent):
import { ReactiveFormsModule } from '@angular/forms';  
@NgModule({  
imports: [  
 // other imports ...  
ReactiveFormsModule  
 ],  
})  
export class AppModule { }
  1. In your component, define and "build" your form dynamically for each row of your table:
import { Component, OnInit, VERSION } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  form: FormGroup;

  members = [
    {
      dataLimit: 'Package 1: Voice',
      value: 0,
      uom: 'Minutes',
    },
    {
      dataLimit: 'Package 2: SMS',
      value: 0,
      uom: 'Units',
    },
  ];

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    const myFields = this.buildFormFieldsFormGroup();
    console.log('myFields: ', myFields);

    this.form = myFields;
  }

  private buildFormFieldsFormGroup(): FormGroup {
    const membersLength = this.members.length;
    let response: FormGroup = this.fb.group({ dummy: ['', []] });

    for (let i = 0; i < membersLength; i++) {
      response.addControl(`field${i}`, new FormControl());
    }
    console.log('response: ', response);

    return response;
  }
}
  1. Add the form and formControls to your HTML:
<div>
  <form [formGroup]="form">
<table>
  <thead>
    <tr>
      <th></th>
      <th>Value</th>
      <th>Unit of Mesure</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let member of members, let i=index">
      <td>{{ member.dataLimit }}</td>
      <td><input type="text" value="{{ member.value }}" formControlName="field{{i}}" /></td>
      <td>{{ member.uom }}</td>
    </tr>
  </tbody>
</table>
</form>
</div>
  1. To verify that everything is functioning correctly, add this at the end of your HTML:
FORM VALUE: {{ form.value | json }}

After entering values into the table, you will see them reflected in the corresponding fields, just like in this screenshot: https://i.sstatic.net/Useke.png

You'll find the first row's value in the form under its "field0" field, and so forth... (NOTE: The 'dummy' field remains in the form for now as a placeholder. In the future, I plan to refine the code to remove this unnecessary element. However, currently, it does not impact the functionality of the form.)

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

Is it possible for the Chrome debugger to locate TypeScript files that have not been served by the

I am creating .js.map files to assist in debugging my TypeScript code within Chrome. The js.map files specify the correct location of the TypeScript in the "sources" property. sourceRoot is set to "", and sources represent the path to the TypeScript code ...

The Array Find method in TypeScript does not always provide the accurate result

I am working with a list of data containing various attributes like latitude, longitude, title, and pair status. [0: {lat: "37.829998", lng: "-122.003152", title: "Allocate", pairStatus: 1, …} 1: {lat: "37.829998", lng: "-122.003152", title: "Commissio ...

Why does the HttpErrorResponse consistently show "OK" in the statusText field?

Constantly Receiving StatusText: "OK" I recently configured HTTPS SSL certification for testing purposes, but I keep getting the "OK" status in StatusText. Ideally, it should return "Bad Request" or "Unauthorized"...etc. I would appreciate some ...

Utilizing Angular: Invoking a function from a directive within a component

I'm attempting to invoke a method from a directive. Let's assume I have a directive myDirective.ts @Directive({ selector: '[something]', }) export class myDirective implements OnInit { .... public myMethod(){ console.log("it works") } ...

«IntelliJ: Effortless Live Reload with Spring Boot and Angular»

For my software development projects, I often work with a spring boot maven project alongside an Angular 5 project. To optimize the workflow, I usually start by building the "dist" folder using the npm run build:prod command and then incorporating it into ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

Modifications to one-to-many or many-to-one connections in typeorm may result in inadvertent null values being set or the updates not being applied at all

After searching through various posts with similar issues, none of the solutions seem to work for my specific problem. It's possible that I may be missing something, which is why I'm reaching out for assistance. Describing the Functionality With ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Can JavaScript and CSS be used to dynamically style textarea content as it is being typed by the user?

I am wondering if it is possible to apply styling to content in a textarea as a user inputs text. For instance: <textarea>abcdefghijklmnopqrstuvwxyz</textarea> Is there a way to highlight all the vowels in the textarea string above using jav ...

When conditional types are used to pass unions through generics, the assigned value defaults to 'any' instead of

In search of a universal type to implement in my actions. Actions can vary from simple functions to functions that return another function, demonstrated below: () => void () => (input: I) => void An Action type with a conditional generic Input h ...

Angular 2: Changing HTTP Requests

I am trying to include a single parameter in all my web requests to disable caching forcibly. My goal is to append ?v=1535DC9D930 // Current timestamp in hex to the end of each request. I am coding this in plain ES5 JS, but the documentation is in Types ...

The navigator.onLine function only checks for devices connected to a system, not specifically connected to the internet

My approach to checking internet connectivity using navigator.onLine only seems to work for determining if my system is connected to a wifi network, not necessarily the internet itself. For example, it may return true even when connected to wifi but with ...

Firebase does not serve as the host for all the webpages within an Angular 4 project

Currently, I am immersed in a project which involves deploying a website using Firebase. The website is utilizing Firebase's Authentication and Database features. For those interested, here is the GitHub link and here is the live site. Despite follow ...

Developing a search feature using Angular 6 with Observable subscription for the FrontEnd application

I have a unique challenge where I need to implement a full text search in the FrontEnd due to restrictions with the API. When the frontend starts up, it fetches all data entries from the Backend and subscribes them inside a component using an async pipe. T ...

Determining the chosen numeral and letter in Angular 8

I am encountering an issue with the selected option, where the name_step = "ABCD" is selected, but when the name_step = "1" is not selected. I am puzzled as to why this is happening, despite setting both as strings. Here is my code snippet: <option ...

Issue with Typescript and React: Property not found on type 'IntrinsicAttributes'

While working on my app using Meteor, React, and Typescript, I encountered a transpiling error: The property 'gameId' is not recognized in the type 'IntrinsicAttributes & {} & { children?: ReactNode; } In my project, I have a com ...

What is the best way to import types from a package that is not usually imported globally?

I like to use the import statement only for importing actual functionality in a file, and I rely on my tsconfig to include all necessary types. Here is an example of a reducer in my application: import { createReducer } from '@ngrx/store'; con ...

Is "This" sufficient as the return type in TypeScript?

During my experimentation with method chaining, I discovered that it is possible to use "this" as a return type. How interesting! Let's take a look at an example: class Shape { color: String; setColor(value: string): this { //Shape won&apos ...