Dynamic data manipulation with Angular ReactiveForms

One of the challenges I am facing involves using formArray for my list of products. Specifically, I am trying to access the value of product_code in my .ts file similar to [ngModel] so that I can manipulate the data accordingly. Can anyone provide guidance on how to achieve this?

<tbody formArrayName="products">
 <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i">
   <th scope="row">{{i+1}}</th>
    <td><input type="text" class="form-control" placeholder="Product Code" formControlName="product_code"></td>
    <td><input type="text" class="form-control" placeholder="Product Name" formControlName="product_name"></td>
    <td><button type="button" class="btn btn-danger ml-2" (click)="deleteProduct(i)">Remove</button></td>
 </tr>
</tbody>

.ts code:

ngOnInit() {
const product = this.fb.group({
      product_code: [],
      product_name: [],
      product_price: [],
      product_quantity: [1],
      product_total: []
    });

 this.myForm = this.fb.group({
  products: this.fb.array([product]),
 }
}
  get productForms() {
    return this.myForm.get('products') as FormArray;
  }

  addProduct() {
    const product = this.fb.group({
      product_code: [],
      product_name: [],
      product_price: [],
      product_quantity: [1],
      product_total: []
    });

    this.productForms.push(product);
  }

  deleteProduct(i) {
    this.productForms.removeAt(i);
  }

To further demonstrate my issue, you can refer to this image: https://i.sstatic.net/xJfvn.png

My main goal is to retrieve the value of product_code, perform a certain function on it, and then assign the result to product_name. While I am familiar with achieving this using ngModel for two-way bindings, I am unsure how to accomplish it using FormControl or Reactiveforms. Any insights would be greatly appreciated.

Answer №1

Learning how to iterate through products and retrieve the product_quantity value:

const product = this.fb.group({
    product_code: [],
    product_name: [],
    product_price: [],
    product_quantity: [1],
    product_total: []
});

const form = this.fb.group({
    products: this.fb.array([product]),
});

const productsArray = form.controls.products as FormArray;
const productsNumber = productsArray.controls.length;
for (let i = 0; i < productsNumber; i++) {
    const productGroup = productsArray.controls[i] as FormGroup;
    console.log(productGroup.controls.product_quantity.value);
}

@Edit 1 The above sample retrieves the value at the moment it is requested.

Here is a way to continuously track changes:

for (let i = 0; i < productsNumber; i++) {
    const productGroup = productsArray.controls[i] as FormGroup;

    productGroup.controls.product_code.valueChanges.subscribe(val => {
        // Update product name whenever product code changes
        productGroup.controls.product_name.setValue(val + 'some value');
    });
}

@Edit 2 Updated the addProduct method to respond to newly added controls:

addProduct() {
    const product = this.fb.group({
        product_code: [],
        product_name: [],
        product_price: [],
        product_quantity: [1],
        product_total: []
    });

    product.controls.product_code.valueChanges.subscribe(val => {
        // Whenever value of product code changes update product name
        product.controls.product_name.setValue(val + 'some value');
    });

    this.productForms.push(product);
}

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

Transforming a detailed JSON structure into a more simplified format with Angular 2

As a newcomer to Angular 2, I find myself encountering a hurdle in filtering unnecessary data from a JSON object that is retrieved from a REST API. Below is an example of the JSON data I am working with: { "refDataId":{ "rdk":1, "refDataTy ...

What could be causing this error for my NPM module in a .NET Core project using Typescript?

My Typescript configuration seems to be causing some issues, even though everything works fine without TS. Could the problem lie in my .d.ts file? And do I really need it for webpack? I have a basic NPM module: index.js: var MyMathTS = function(a, b){ ...

Implementing TypeScript type declarations for merging core types

Is there a way to perform type declaration merging in TypeScript for built-in types when using imports? I am currently attempting to merge interfaces as per the guidelines outlined in this documentation: https://www.typescriptlang.org/docs/handbook/declar ...

Angular: using the filter pipe to render HTML content

When using the pipe, I encounter an issue where the css is not being applied to highlight the searched words in a list. Instead of displaying the yellow background for the searched words, it outputs and displays the tag below: <span class='highlig ...

Ways to modify environment variables in Angular 6 without the need to rebuild

Typically, I store my API URLs in the environment.ts file. However, when deploying builds to multiple clients with different API URLs, I find myself creating separate builds for each client after adjusting the environment variables. Is there a solution th ...

The documentation for Angular guards is riddled with vague and obfuscating statements

I've been delving deep into Angular lately, and I found the documentation to be quite enlightening. currently, I'm focused on learning about guards. In my research, I came across this intriguing statement: The router evaluates CanDeactiva ...

There seems to be an issue with the Angular zone.js and zone-evergreen.js files showing an error that reads:

My Angular 11 app suddenly started showing errors across all browsers and environments (local, staging, prod) about an hour ago without any updates: Uncaught TypeError: t.getElementsByTagName is not a function at computeStackTrace.js:338 at Array.f ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Having trouble activating the ENTER key press event listener for the QuillJS editor in Angular 4 and above

I have been trying to set up an event listener for the ENTER key press in QuillJS using addBinding as described in the official documentation here. However, despite successfully configuring listeners for other keys like BACKSPACE, I am unable to get the EN ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Encountering a problem while implementing ngFor in Angular 4

Issue with ngFor Loop in Angular 4 Does anyone have insight into why this error is appearing in the console despite data being displayed? The data is showing, but an error is still being thrown empresas = <Empresa> {}; constructor(private servi ...

Awaiting the completion of Promises within a for-loop (Typescript)

I'm struggling with a for-loop and promises in my angular2 project. I have multiple methods that return promises, and after these promises are resolved, I want to populate an array in the class using Promise.all(variable).then(function(result){....... ...

Navigate back two levels (../../) using Angular2's relative navigation

One issue I am currently experiencing with my application is related to the functionality of a back button that navigates back through multiple levels. When navigating back one level, the code snippet below works perfectly, resulting in a route URL of http ...

What is the reason for storing a base64 string as an Object in a MongoDB database?

I am facing an issue with storing a product detail on the mongoDB database. When I try to save it, mongoDB stores a property imageSrc as an object instead of a string. Here is my database This is my angular service And this is my express server request ...

Sequelize's bulk synchronization process is ineffective

I am facing an issue with getting sequelize.sync() to function properly. When I call sync() for each model definition individually, it works perfectly fine. However, when trying to execute it from the sequelize instance itself, it seems like the registered ...

Getting the current browser window in the renderer within Electron 14: A step-by-step guide

Previously, I utilized the code below to retrieve the current window from the renderer: import {remote, BrowserWindow} from 'electron'; export function getCurrentWindow(): BrowserWindow { return remote.getCurrentWindow(); } With electron 14 ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Tips to prevent unexpected surprises during npm installation or updates

What is the best approach for safely npm installing/updating when deploying or upgrading? Issue 1 : Running npm install relies on the latest versions of dependencies at the time of execution, leading to unexpected results during deployment as the packa ...