The process of retrieving input field values from a table within an Angular reactive form

I am seeking a way to collect all input values found within the table rows inside a reactive form. Below is an explanation of my code.

<form [formGroup]="productForm" (ngSubmit)="saveProduct($event)" novalidate>
<mat-form-field appearance="outline">
   <mat-label>Product Name</mat-label>
   <input matInput placeholder="Product Name" aria-label="Product Name" formControlName="ProductName" maxlength="70" required>
</mat-form-field>
<div class="section" *ngIf="productForm.get('ProductType').value == 'C' && isConfigSection==1">
   <div class="help-content">
      <h5>Configurables</h5>
   </div>
   <div class="form-content">
      <div class='col-sm-12' style="max-width: 100%;">
         <div id="table-scroll" class="table-scroll">
            <div class="table-wrap">
               <table class="main-table">
                  <tbody *ngIf="ColumnNames.length > 1">
                     <tr *ngFor="let opt of ConfigArr; let i = index;">
                        <td class="sticky-col first-col">
                           {{opt.attrName1}}({{opt.attr1}})
                        </td>
                        <td class="sticky-col second-col">
                           {{opt.attrName2}}({{opt.attr2}})
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add MRP" aria-label="MRP" [(ngModel)]="opt.MRP">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add BaseUnitPrice" aria-label="BaseUnitPrice" [(ngModel)]="opt.BaseUnitPrice">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add DiscountValue" aria-label="DiscountValue" [(ngModel)]="opt.DiscountValue">
                        </td>
                        <td>
                           <input class="form-control" class="form-control" matInput placeholder="MinBuyQty" aria-label="MinBuyQty" [(ngModel)]="opt.MinBuyQty">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add MinimumPrice" aria-label="MinimumPrice" [(ngModel)]="opt.MinimumPrice">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add TaxPercentage" aria-label="TaxPercentage" [(ngModel)]="opt.TaxPercentage">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add TaxAmount" aria-label="TaxAmount" [(ngModel)]="opt.TaxAmount">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add DiscountPrice" aria-label="DiscountPrice" [(ngModel)]="opt.DiscountPrice">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add MaxBuyQty" aria-label="MaxBuyQty" [(ngModel)]="opt.MaxBuyQty">
                        </td>
                        <td>
                           <input class="form-control" matInput placeholder="Add MaximumPrice" aria-label="MaximumPrice" [(ngModel)]="opt.MaximumPrice">
                        </td>
                        <td>
                           <button class="btn btn-md btn-primary" type="button" (click)="addImage($event, AddImages,i)">
                           Add Image<i class="fa fa-plus"></i>
                           </button>
                        </td>
                     </tr>
                  </tbody>
               </table>
            </div>
         </div>
      </div>
   </div>
</div>
</form>

Below is my TypeScript code:

for(let i=0; i< res['data']['Attributes'][this.ColumnNames[0]].length;i++){
   for(let j=0;j< res['data']['Attributes'][this.ColumnNames[1]].length;j++){
       let data = {
                  'attr1':res['data']['Attributes'][this.ColumnNames[0]][i],
                  'attrName1':attrName1,
                  'attr2': res['data']['Attributes'][this.ColumnNames[1]][j],
                  'attrName2': attrName2,
                  "MRP": '',
                  "BaseUnitPrice":'',
                  "DiscountValue": '',
                  "MinBuyQty":'',
                  "MinimumPrice":'',
                  "TaxPercentage":'',
                  "TaxAmount":'',
                  "DiscountPrice":'',
                  "MaxBuyQty":'',
                  "MaximumPrice":''
                }
                this.ConfigArr.push(data);
   }

I am in the process of preparing an array for the table. Within this table are input fields. Upon form submission, I would like to retrieve the input values for each row within that same array. Although I am using [(ngModel)], it does not seem to work within the Angular reactive form. My goal is to capture user input values for each row in the table upon submission of the form.

Answer №1

` ngOnInit() {
    this.survey = new FormGroup({
      surveyName: new FormControl(''),
      logoUrl: new FormControl(''),
      headerUrl: new FormControl(''),
      headerColor: new FormControl(''),
      footerUrl: new FormControl(''),
      footerColor: new FormControl(''),
      sections: new FormArray([
        this.initSection(),
      ]),
    });
  }

  initSection() {
    return new FormGroup({
      sectionTitle: new FormControl(''),
      sectionDescription: new FormControl(''),
      questions: new FormArray([
        this.initQuestion()
        ])
    });
  }
  initQuestion() {
    return new FormGroup({
      questionTitle: new FormControl(''),
      questionType: new FormControl('',Validators.required),
      options: new FormArray([
        this.initOptions()
      ])
    });
  }

  initOptions() {
    return new FormGroup({
      optionTitle: new FormControl('')
    });
  }

  addSection() {
    const control = <FormArray>this.survey.get('sections');
    control.push(this.initSection());
  }`

https://stackblitz.com/edit/deep-nested-reactive-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

Angular4's integration with AngularFireAuth for Google authentication is causing users to be redirected back to the source page before they can successfully

Previously, this feature was functioning perfectly. However, the current issue is that the browser is redirecting to a long URL and then quickly returning to the original source URL. This prevents users from logging into their Google accounts. authentica ...

Angular4 Leaflet Map encountering errors

Here is the template: <div id="mapid" style="height: 500px"></div> After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import. This is the cont ...

I'm having trouble with ViewChild - consider upgrading to beta7 for a solution

import {Page,NavController,NavParams,Platform,IonicApp} from 'ionic-angular'; import {ViewChild} from '@angular/core'; @Page({ templateUrl: 'build/pages/tabspage/tabspage.html' }) @ViewChild('myTabs') tabRef: T ...

Encountering a 404 error when trying to load a script from a local folder into a component

I've been attempting to load a JavaScript file into a component. When the file is placed outside the 'src' folder, everything works perfectly. However, when it's inside the 'src' folder, I keep getting a 404 error. I've t ...

Angular 5 ngIfElse: How to save the outcome of a condition in a storage container

Code Snippet: <mat-icon [ngClass]='{ rotate: !users }'>refresh</mat-icon> <div *ngIf="usersObservable | async as users; else loading"> ... </div> <ng-template #loading let-users> Waiting... </ng-template> ...

Should I link my Angular Material 2 data table to AngularFire2 or Firebase service?

Trying to make this work has been quite the struggle. I've spent hours experimenting, but nothing seems to be working as expected. The md data table is relatively new, so there isn't much information available online yet. Connecting Firebase to t ...

Spontaneous visual paired with text upon refreshing

I am new to Java script and I am working on creating a web page that displays two random numbers every time it is refreshed. Depending on these numbers, specific text should be shown. These numbers are represented by images ranging from 0 to 5. Currently ...

Encountering a Problem with Angular 2 Directive *ng-for

Recently started experimenting with the beta version of Angular 2.0 and encountered an error stating "angular is not defined" while trying to add directive: [angular.ngFor]. If you want to take a look, here is the Plunker URL: http://plnkr.co/edit/ULHddLR ...

Utilizing Angular's microservice architecture to dynamically load modules from a provided

Recently, I've been contemplating the best way to integrate Angular into a microservices architecture. Imagine we have separate services for login, user management, and media browsing, adding, and editing - each with its own backend and frontend in i ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

6 Ionic date-time selector

I seem to be encountering some challenges while using Ionic 6 with the new date-time picker. The issue arises when I retrieve a value from the database through a nest service. In the database, the date appears as: “2022-06-30 13:11:54” but upon retriev ...

Looking to adjust the height of a foreignObject element within an SVG?

Looking to dynamically change the height of a foreignObject within an SVG, while also needing HTML elements inside it (working with ngx-graph). <foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Dat ...

Adjusting box width based on device type: desktop and mobile

I'm currently working on a form that includes several mat-form-fields. I have set the width of these items to 750px, but this does not work well for mobile devices. I am trying to figure out how to make the form or mat-form-field automatically adjust ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

Issue with PrimeNG DataTable contextMenu alignment inside TabView

I encountered an issue with displaying a DataTable - contextMenu when it is placed within a TabView. The contextMenu was appearing off-center. However, the DataTable - contextMenu worked perfectly fine when it was not wrapped in a TabView. To address this ...

Efficient management of npm dependencies versioning using Git workflow with Angular

In my Angular project, we combine multiple locally created artifacts that are published to the npm repository. Within the "dependencies" section of my app's package.json file, I include the following: "@k/e-lib": "^0.3.0", "@k/et-lib": "^0.3 ...

Dealing with Angular API Requests and Handling Cors Exception in C# Web API

My goal is to call an API on my C# Web API from my Angular Frontend. I have attempted making the call using both HTTP and HTTPS. When using HTTP, I encounter a CORS exception. On the other hand, when using HTTPS, I receive a CONNECTION CLOSED EXCEPTION. ...

Using the async pipe with the ngIf directive

When the AsyncPipe is used within an *ngIf, there may be issues if the Observable associated with the AsyncPipe emits its values before the *ngIf statement evaluates to true. For instance, consider the following scenario: <div *ngIf="showData"> ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...