Issue encountered while trying to insert a new row into the mat-table

I need help with inserting a new row in mat-table using a button. I wrote a function for this, but when I click the button, I encounter an error

CalculatoryBookingsComponent.html:62 ERROR Error: Cannot find control with path: 'rows -> 0'
. Additionally, only the first 5 cells are displayed. Can someone assist me in understanding and fixing this issue?

Here is where I'm working on it: https://stackblitz.com/edit/angular-l9x7ac?file=app%2Ftable-basic-example.html

Snippet of the code:

// HTML

<button class="crud-status" type="submit" mat-raised-button (click)="addRow()">add</button>
<td mat-cell *matCellDef="let row; let i = index;">
                <div formArrayName="rows" *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns"> // Line 62: This is the area where the error code points to
                  <span class="edit-cell" [formGroupName]="i">
                      <mat-form-field>
                        <label>
                          <input matInput type="text" [formControlName]="column.attribute">
                        </label>
                      </mat-form-field>
                  </span>
                </div>
                <ng-template #otherColumns>
                  {{ column.object  !== null ? row[column.object][column.attribute] : row[column.attribute]  }}
                </ng-template>
              </td>

// TS

// ********** DATA TABLE ARRAYS **********//

  private beforeMonthsColumns: EditColumns[] = [
    { attribute: 'name', name: 'Erlöse / Kostenarten', object: null, disabledRanges: false, disabledAssignment: false },
    { attribute: 'kagNumber', name: 'KAG', object: null, disabledRanges: false, disabledAssignment: false }

  ];
  private monthColumns: EditColumns[] = [
    { attribute: '1', name: 'Jan', object: 'values', disabledRanges: false, disabledAssignment: false },
    { attribute: '2', name: 'Feb', object: 'values', disabledRanges: false, disabledAssignment: false },
    { attribute: '3', name: 'Mrz', object: 'values', disabledRanges: false, disabledAssignment: false }
  ];
  private afterMonthsColumns: EditColumns[] = [
    { attribute: 'note', name: 'Anmerkung', object: null, disabledRanges: false, disabledAssignment: false },
    { attribute: 'assignment', name: 'zugeordnet? KAG', object: null, disabledRanges: false, disabledAssignment: true }
  ];

  // Merged arrays
  public displayedColumns: EditColumns[] = [
    ...this.beforeMonthsColumns,
    ...this.monthColumns,
    ...this.afterMonthsColumns
  ];

 addRow() {
    this.dataSource.data.push(this.columns[this.index++])
    this.table.renderRows()
  }

 const formRowsData = [];
              const nameFormArray = this.calcBookingsForm.get('rows') as FormArray;
              // build form array values for text fields in data table rows
              for (const formRowDataEntry of formRowsData) {
                const consolidatedValues = {};
                // Combine rows values into one object
                for (const d of formRowDataEntry) {
                  consolidatedValues[d.attr] = d.value;
                }
                // bind values of one row to a form control group
                const rowGroup = this.formBuilder.group(consolidatedValues);
                nameFormArray.push(rowGroup);
                rowGroup.valueChanges.subscribe((rowData) => {
                  console.log('Row data changed:', rowData);
                });
              }
              this.dataSource.data = rows;

Answer №1

To maintain consistency, ensure that your FormArray values are in sync with the array in the table DataSource:

ngOnInit() {
  ...
  this.myForm = this.formBuilder.group({
    rows: this.formBuilder.array([this.initItemRows()])
  }); 

  this.dataSource.data = this.myForm.get('rows').value;
}

addRow() {
  const newItem = this.initItemRows();
  this.formArr.push(newItem);

  this.dataSource.data = this.dataSource.data.concat(newItem.value);
}

Take a look at the Forked Stackblitz

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

Can you identify the type of component being passed in a Higher Order Component?

I am currently in the process of converting a protectedRoute HOC from Javascript to TypeScript while using AWS-Amplify. This higher-order component will serve as a way to secure routes that require authentication. If the user is not logged in, they will b ...

Change prompt-sync from require to import syntax

In my Node project, I have integrated the prompt-sync module. const prompt = require('prompt-sync')(); const result = prompt(message); To maintain consistency in my TypeScript code, I decided to switch from using require to import. In order to ...

Maintaining security and privacy with Angular 5: Ensure localStorage is cleared when the browser

In my web application using Angular 5, I have a requirement to clear the localStorage objects whenever the user closes the browser window. @HostListener("window:beforeunload", ["$event"]) clearLocalStorage(event) { localStorage.clear(); console.lo ...

Managing Angular routing: selectively updating named outlets without reloading submodules

My routing configuration currently reloads Module2 ListComponent on every routing event. However, I want to prevent the list from reloading when a user clicks on a list item within ListComponent. Specifically, when navigating from module2/route1 to module ...

Can the PrimeNG p-fileUpload component be configured to launch from a specific directory?

Utilizing the PrimeNG p-fileUpload component for file uploads. Looking to customize the default folder that opens when the select file button is clicked. Would like it to open in a specific location such as Desktop or Videos. Is there a method to achieve ...

Updating JWT token with Angular 5 Http Interceptor

I have successfully implemented token saving, retrieving logic and a refreshing call. However, I am facing an issue where when I intercept a 403 error in my HttpInterceptor, other simultaneous calls also trigger a token refresh. I would like to find a wa ...

The functionality of md-checkbox is not compatible with ng-click

I need to store the position every time a checkbox is changed: <h1 class="md-display-2">Simple TODO ng app</h1> <h2 class="md-display-3"></h2> <div ng-include src="'todo/add.html'"></div> <div> &l ...

Creating a new section in an Angular 2 project can be achieved by implementing an onclick function that is

Whenever I click the new button, a section with 3 fields should appear. However, even though I am not receiving any errors, I can't seem to figure out what I'm doing wrong. Click here for an example Here is the HTML: <form *ngFor="let ...

Implementing Ionic Native Player for Practical Applications

Looking for a way to incorporate a lightweight mp3 file into my Ionic App, I decided to utilize Native Audio from Ionic. Despite my best efforts, the solution did not function properly on the iOS emulator when called from /MyIonicApp/src/pages/home/home.ts ...

Tips for customizing the event target appearance in Angular 2?

After following the steps outlined in this particular blog post (section 3, event binding), I successfully added an event listener to my component class. I can confirm that it responds when the mouse enters and exits. <p class="title" (mouseenter)="unf ...

Guide to accessing contact list on Ionic framework

I'm new to using Ionic and I'm trying to access the contact list in my app to display contacts only. Can someone please guide me on how to achieve this? I watched a tutorial on YouTube but the code provided doesn't seem to work. I've ad ...

Props used in styled components are effective, although they may trigger a warning message stating, "Warning: Received `true` for a non-boolean attribute `cen`."

Caution: A non-boolean attribute "cen" received a value of "true". If you intend to render it in the DOM, provide a string instead: cen="true" or cen={value.toString()}. While using Props in Styled-Component with TypeScript and Material-UI, everything func ...

Having trouble executing a method from a template in Angular 5?

Angular has a useful capability that almost every developer has utilized at some point: calling methods from templates. I've personally been using this feature for months without any issues. However, recently I encountered a problem. I have a menu co ...

Having difficulty loading Angular2/ Tomcat resources, specifically the JS files

I am currently in the process of deploying my Angular2 web application on a Tomcat server. After running the ng build command, I have been generating a dist folder and uploading it to my Tomcat server. However, whenever I try to run my web app, I encounte ...

An issue has occurred due to an illegal state while attempting to utilize two modules within a single

When a user logs into my system, they are redirected to the profile page /profile/profile.component.ts after entering correct login credentials. Now, I want to implement an additional module for protected pages/components like the profile page and redirect ...

Angular aggregates information from numerous HTTP inquiries

I am looking to retrieve data for multiple ProductIds from a remote source using httpClient in an angular service. My goal is to merge the data within the service and then send it back. When working with just one productId, everything functions correctly: ...

Exploring the Power of TextEncoding in TS 2.8 within the Angular 6 Environment

I'm facing a challenging issue while trying to import TextEncoding in TS 2.8. I have installed it using npm and attempted to import it like this: import { TextDecoder } from 'text-encoding'; Alternatively, import { } from 'text-encod ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

Angular: Converting this code into a loop - A step-by-step guide

Currently, I am in the process of learning Angular along with its Angular Material UI Framework. Following the installation of dependencies, I created a Material Rank Table using the command below: ng generate @angular/material:table rank-table --module=ap ...

A guide on assigning specific (x, y) coordinates to individual IDs within the tree structure

When attempting to calculate the positions of each ID in order to arrange them hierarchically on the canvas, I encounter some challenges. Whether it's organizing them into a tree structure or multiple trees resembling a forest, one restriction is that ...