Show information in a table by utilizing FormArray

Displaying data retrieved from the database, the image shows some input fields. However, an issue arises when trying to input values as the focus on the input field is disabled. Assistance needed to resolve this problem.

Code Example (HTML):

<table class="table table-striped table-hover table-bordered table-sm" id="mytable">
    <thead>
        <tr>
            <th style="text-align: center;" scope="col">
                Item Id
            </th>
            <th style="text-align: center;" scope="col">
                Item Name
            </th>
            <th style="text-align: center;" scope="col">
                Quantity
            </th>
            <th style="text-align: center;" scope="col">
                Buying Price Rs:
            </th>
            <th style="text-align: center;" scope="col">
                Amount Rs:
            </th>
            <th style="text-align: center;" scope="col">
                Status
            </th>
            <th style="text-align: center;" scope="col">
                Action
            </th>
        </tr>
    </thead>
    <tbody>
        <tr formArrayName="credentials"
            *ngFor="let creds of grnGroup.controls.credentials?.value; let i = index">
            <td style="text-align: center;" [formGroupName]="i">
                <b>{{creds.itemId }} </b>
            </td>
            <td style="text-align: center;" [formGroupName]="i">
                <b>{{ creds.itemName }}</b>
            </td>
            <td style="text-align: center;" [formGroupName]="i">
                <b>{{ creds.qty }}</b>
            </td>
            <td style="text-align: center;" [formGroupName]="i">
                <input type="text" formControlName ="price" class="form-control" size="5"/>
            </td>
            <td style="text-align: center;" [formGroupName]="i">
                <b>{{ creds.amount }}</b>
            </td>
            <td [formGroupName]="i" *ngIf="'Pending' == creds.status"
                style="color:Gold; text-align: center; ">
                <i class="fa fa-spinner" aria-hidden="true"></i>
            </td>
            <td [formGroupName]="i" *ngIf="'Approved' == creds.status"
                style="color:green; text-align: center; ">
                <i class="fa fa-thumbs-up" aria-hidden="true"></i>
            </td>
            <td style="text-align: center;" [formGroupName]="i">
                <button type="button" class="btn btn-success btn-sm"
                    (click)="pushValue(creds[i])">
                    <i class="fa fa-check" aria-hidden="true"></i>
                </button>
            </td>
        </tr>
    </tbody>
</table>

TypeScript Code:

 ngOnInit() {
this.grnGroup = this.formBuilder.group({
    credentials: this.formBuilder.array([]),
}) }

 const tableData = this.formBuilder.group({
                        itemId:[itemId] , itemName:[itemName] ,qty:[qty] , amount:[amount] ,status: [this.array[i].status] ,price:['']
                    });

   this.GRNForms.push(tableData);

  get phoneForms() {
        return this.grnGroup.get('credentials') as FormArray
      }

https://i.sstatic.net/FxweE.jpg

Answer №1

One issue arises when the value of a form changes, causing the reference of that value to also change. As a result, Angular redraws the ngFor items, causing the loss of focus.

This can be prevented through two methods:

  1. Add trackBy: onTrackById to *ngFor
*ngFor="let creds of grnGroup.controls.credentials?.value; trackBy: onTrackById; let i = index"

In the component.ts file:

onTrackById(index: number, item: FormGroup) {
   return index; // or use a unique value like (item.get('id').value)
}
  1. Replace
    grnGroup.controls.credentials?.value
    with
    grnGroup.get('credentials').controls
*ngFor="let creds of grnGroup.controls.credentials?.controls; trackBy: onTrackById; let i = index"

A simple example with console logs demonstrating the issue and solution can be found in this link:

https://stackblitz.com/edit/form-array-angular-rdg8dd

Answer №2

It appears that you are attempting to add the new control directly to the form instead of the formArray. Consider using the following approach:

this.GRNForms.get('credentials').push(tableData);

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 to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Angular POST method encountered an error

When attempting to execute a post method, it works fine using the Postman App, but I encounter an error when trying to do this in Angular. Below is my POST Service code snippet: storeServers(comment) { console.log(comment); var headers = new Headers(); h ...

How do I use [(ngModel)] to set custom multiple select with 'selected' options with Angular and Materialize CSS?

Below is a snippet of code I am working with: <div class="input-field col s12"> <select name="uniqueName" [(ngModel)]="model.servicesIds" multiple> <ng-container *ngFor="let service o ...

HTML elements are failing to display when utilizing the Angular selector

I'm currently working on a project with Angular 2/4 and I'm running into an issue with rendering the app.component.html in the main index.cshtml page. All I can see is the word "loading" that is hard-coded in the index.cshtml file. I've doub ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Learn the process of automatically including correlation headers in Angular HTTP requests for Application Insights

I am currently utilizing the npm package @microsoft/applicationinsights-web within my Angular project. In my http service, I have custom headers that seem to be overriding the correlation headers ('Request-Id' and 'Request-Context'). D ...

What is causing the issue with entering the code? Exploring the restrictions of the mui tag

Can someone explain why I am unable to use boolean data type in this code snippet? I am trying to determine whether the user is an admin or not, and based on that, hide or disable a button. const Authenticate = useSelector(userSelector) let checkValue ...

Combining Angular 4 with a pre-existing Spring Boot web app utilizing JSP components

Currently, I have a live Spring Boot web application that uses jsp and JavaScript. My goal is to gradually update existing pages with Angular when time allows. While I am new to Angular, most of the information I have come across suggests that it require ...

The comparison of Booleans in Typescript sometimes produces inaccurate results

There is a strange issue I encountered in one of my classes involving a readonly boolean property. Whenever I try to check this property, the results are not as expected. Here is an example of the code: // vorgang is a reference to the class, isEK is the ...

Eradicate lines that are empty

I have a list of user roles that I need to display in a dropdown menu: export enum UserRoleType { masterAdmin = 'ROLE_MASTER_ADMIN' merchantAdmin = 'ROLE_MERCHANT_ADMIN' resellerAdmin = 'ROLE_RESELLER_ADMIN' } export c ...

Managing the sequence of module loading in NodeJS

Consider this scenario: There are 3 files (modules) involved: app.js (async () => { await connectoDB(); let newRec = new userModel({ ...someprops }); await newRec.save(); })(); The app.ts serves as the entry point of the project. database ...

Ways to retrieve schema in a Kafka consumer while utilizing schema registry?

I'm currently in the process of incorporating Kafka into our microservices setup. We have opted to use Karaspace as our schema registry, and protobuf as the data format. The producer microservice contains a .proto file defining the schema that needs t ...

I am attempting to integrate Spine into my Pixi.js project, but I am encountering an unexpected issue

Hey there, I'm currently exploring how to incorporate Spine into my pixi.js application. The main issue I'm facing in my project is that every time I try to initialize Spine in a file, I encounter a single error https://i.sstatic.net/LhxmGmxd.pn ...

I'm having trouble with the installation of Angular on my Linux

npm WARN EBADENGINE Unsupported engine { '@angular/[email protected]' required: { node: '^12.14.1 || >=14.0.0', npm: '^6.11.0 || ^7.5.6', yarn: '>= 1.13.0' }, current: { node: 'v10.19.0', npm: ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Learning how to interpret jsonpickle data within an Angular TypeScript file

I am currently developing a hobby application that uses Angular for the front-end and Python for the back-end. In this setup, a component in Angular sends an HTTP GET request to Python, which responds with a jsonpickled object. My goal is to decode the js ...

Update a MongoDB collection with data retrieved from a JavaScript object mapping

I have come across a collection that has the following structure: [ { "project":"example1", "stores":[ { "id":"10" "name":"aa", ...

Exporting a constant as a default in TypeScript

We are currently developing a TypeScript library that will be published to our private NPM environment. The goal is for this library to be usable in TS, ES6, or ES5 projects. Let's call the npm package foo. The main file of the library serves as an e ...

Conditional validation in Angular for template-driven forms allows for dynamic validation rules based

I need to make an input field mandatory only if another value is selected from a dropdown. Below is a simplified example of the relevant parts of my form: Template: <form name="createPaymentForm" (ngSubmit)="f.form.valid && createPayment()" #f ...

Checking if a specific component element is present in the DOM using Jasmine and Angular

Greetings Stack Overflow Community, I've encountered a challenge while attempting to write a basic Jasmine Unit Test in Angular 5 to confirm the presence of an element in the DOM for components. I have successfully tested standard HTML elements like ...