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

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

Not sure of the best location to place the subscription for three observables linked with switchMap?

this._authService.loggedInUser$.pipe(switchMap((loggedInUser: LoggedInUser) => { return this._userSerialService.getUserSerial().pipe(switchMap(serial => { return this._usersService.getCurrentUser().pipe(switchMap(currentUser => [lo ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

Utilizing variables to set the templateUrl in Angular2

Trying to assign a variable to the templateUrl in my component, but it's not functioning as expected. @Component({ selector: 'article', templateUrl: '{{article.html}}', styleUrls: ['styles/stylesheets/article.comp ...

Utilizing conditional types for type narrowing within a function's body: A comprehensive guide

I created a conditional type in my code that constrains the second argument of my class constructor based on the type of the first argument. Although the type checker correctly limits what I can pass to the constructor, I am struggling to get the compiler ...

How are databases and CRUD operations connected?

I am working on developing a database to store data from the web that I can use for various purposes. My goal is to create a project management tool similar to Monday.com online. I have been exploring React CRUD and databases as a starting point for stor ...

Error: the attempt to execute the mongoose connection function has failed due to it not being recognized as a valid function

Hey there, I'm encountering the error TypeError: mongoose__WEBPACK_IMPORTED_MODULE_15___default.a.connect is not a function import mongoose from "mongoose"; const dbURI = 'myurlstuffhere'; mongoose.connect(dbURI , {useNewUrlParser: ...

Having trouble retrieving the URL from the router in Angular 2?

Whenever I try to access the URL using console.log(_router.url), all it returns is a / (forward slash). Here is the code snippet in question: constructor( private el: ElementRef, private _auth:AuthenticationService, @Inject(AppStore) private ...

There was an issue attempting to differentiate '[object Object]'. The Angular API Get Request from .Net only allows for arrays and iterables to be used

I am currently in the learning stage and consider myself a novice, so please forgive me if this question seems silly. I am working on a Movie Database project that involves integrating movies from a live API, creating a favorite list, implementing JWT auth ...

Navigating route parameters in Angular Universal with Java

I am currently developing a web application using Angular 5 with Server Side Rendering utilizing Angular Universal for Java. The project repository can be found here. One of the challenges I am facing is with a parameterized route defined in Angular as /pe ...

Encountering issues with MatToolbar in Angular 9 causes unexpected errors

Running Angular version 9.2.0 Encountering an issue while importing the MatToolbarModule in a module and utilizing it in the HTML template. The error message reads as follows: This could indicate that the library (@angular/material/toolbar) that declar ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

401 error code for all CRUD operations in the .NET Framework API

So, I've been working on a project that consists of a .Net framework API and an Angular frontend. I recently implemented OWIN JWT authentication, but now I'm encountering a persistent 401 error no matter what I try. I've attempted numerous ...

Issues Arise with Nativescript Layout When Content is Not in View on iOS

This problem has been giving me a hard time for the past few days. I hope someone can help me figure out what's wrong. I have a view that shows a nested list inside a main list. The main list contains header details. Everything looks fine when the in ...

Steps to create a clickable row with color change in Angular 4

How do I make an entire row clickable and change the row color when a checkbox is clicked? This is my HTML file: <section class="others"> <div class="sub-header">Others</div> <p class="text-center" *ngIf="otherTests.length === 0"> ...

Loading external libraries in Angular2: A step-by-step guide

I'm currently working on incorporating a Datepicker in Angular 2, but I'm facing an issue where the library is not loading. This is causing a template parsing error stating 'material-datepicker' is not a recognized element: My System.c ...

When using NextJS <Link, mobile users may need to tap twice to navigate

Whenever I use the NextJS <Link tag on my mobile device, I notice that I have to double-tap for the link to actually route to the desired page. Take a look at the code snippet below: <Link href="/methodology" passHref={true} ...

Is it possible for an Angular2 HTTP request to retrieve the response body as binary data?

I'm facing an issue with a URL that returns HTML content with charset=iso-8859-7. Angular's HTTP request converts the data to utf8 by default, making it difficult for me to encode them back in iso-8859-7 properly. Upon researching, I discovered t ...

Issues encountered while attempting to use 'npm install' on Angular, leading to

Having trouble with npm i in my project. It's not working for me, but others can install it smoothly. I've checked all the node and angular versions, but I can't figure out what's missing. Could it be my laptop's compatibility? Ple ...

Unique: "Unique styling for Ionic on emulator versus web localhost"

My perception of CSS codes in browsers versus emulators differs. I believe that currently, CSS codes only work properly in browsers. For instance, I attempted to change -ion-background-color for .md body and iosbody. However, the emulator still displays t ...