Troubleshooting offline pagination with dynamic MatTable containing matInputs (Angular 5 Material Design)

I have an issue with my component that contains an empty form with matInputs, as well as a mat-table with matInputs in the rows, all enclosed in mat-cards.

The number of rows in the table is dynamic and based on another input called 'range'. So, when I set the 'range' value on my matInput, the rows are dynamically created with an offline paginator.

My problem arises when I create 20 rows and decide to display 5 items per page using the paginator. After filling in the matInputs within the table and clicking on the next page, the columns with matInputs retain the values from the previous page. This issue only affects the columns with matInputs and not label columns like the row numbers. I am unsure why this is happening and would appreciate any help!

Here is a link to the sample code:

(https://stackblitz.com/edit/angular-qhp2eg?file=app%2Ftable-http-example.ts)

  • .ts file:

    import {Component, OnInit, ViewChild} from '@angular/core';
    import {MatPaginator, MatTableDataSource, MatSort} from '@angular/material';
    import {FormArray, FormBuilder, FormGroup} from '@angular/forms';
    import {merge, Observable, of as observableOf} from 'rxjs';
    import {catchError, map, startWith, switchMap} from 'rxjs/operators';
    
    /**
     * @title offline table pagination example
     */
    @Component({
      selector: 'example-offline-table',
      styleUrls: ['example-offline-table.css'],
      templateUrl: 'example-offline-table.html',
    })
    export class ExampleOfflineTable implements OnInit {
    
      displayedColumns: string[] = ['position', 'name', 'surname'];
      dataSource = new MatTableDataSource();
      public myFormObject: FormGroup;
      public myUsersTableArray: FormArray;
    
      @ViewChild(MatPaginator) paginator: MatPaginator;
    
      constructor(private fb: FormBuilder) {
        this.myFormObject = this.getBuildForm();
        this.dataSource = new MatTableDataSource();
        this.dataSource.paginator = this.paginator;
      }
    
      ngOnInit() {
      }
    
      getBuildForm(): any {
        return this.fb.group({
          range: [''],
          users: this.fb.array([])
        });
      }
    
      createRowsByRange() {
        const theRange = this.myFormObject.get('range');
        this.myUsersTableArray = this.myFormObject.get('users') as FormArray;
        for (let index = 0; index < theRange.value; index++) {
          const position = index + 1;
          this.myUsersTableArray.push(
            this.fb.group({
              position: position,
              name: [''],
              surname: ['']
            })
          );
        }
        this.dataSource = new MatTableDataSource(this.myUsersTableArray.value);
        this.dataSource.paginator = this.paginator;
      }
    }
    
  • .html file:

    <div class="example-container mat-elevation-z8">
      <form [formGroup]="myFormObject">
    
        <mat-form-field>
          <input matInput type="text" formControlName="range" (change)="createRowsByRange()" placeholder="Range">
        </mat-form-field>
    
        <div formArrayName="users">
          <div class="example-table-container">
    
            <mat-table #table [dataSource]="dataSource">
    
              <!-- Position Column -->
              <ng-container matColumnDef="position">
                <mat-header-cell *matHeaderCellDef>Pos.</mat-header-cell>
                <mat-cell *matCellDef="let row">
                  {{row['position']}}
                </mat-cell>
              </ng-container>
    
    
              <!-- Name Column -->
              <ng-container matColumnDef="name">
                <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
                <mat-cell *matCellDef="let row;  let rIndex = index; ">
                  <mat-form-field [formGroupName]="rIndex">
                    <input matInput type="text" formControlName="name" placeholder="Name">
                  </mat-form-field>
                </mat-cell>
              </ng-container>
    
    
              <!-- Surname Column -->
              <ng-container matColumnDef="surname">
                <mat-header-cell *matHeaderCellDef>Surname</mat-header-cell>
                <mat-cell *matCellDef="let row;  let rIndex = index; ">
                  <mat-form-field [formGroupName]="rIndex">
                    <input matInput type="text" formControlName="surname" placeholder="Surname">
                  </mat-form-field>
                </mat-cell>
              </ng-container>
    
              <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
              <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
            </mat-table>
    
            <mat-paginator [pageSizeOptions]="[5, 10, 15]"></mat-paginator>
    
          </div>
        </div>
      </form>
    </div>
    

Thank you for your assistance!

Answer №1

Understood!
Just make sure to update the formGroupName (index array) to match the row's position:

<ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let row;">
        <mat-form-field [formGroupName]="row['position']">
            <input matInput type="text" 
            formControlName="name" placeholder="Name">
        </mat-form-field>
    </mat-cell>
</ng-container>

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

Standard layout for a project with equally important server and client components

We are in the process of developing an open-source library that will consist of a server-side component written in C# for Web API, meta-data extraction, DB operations, etc., and a client-side component written in TypeScript for UI development. Typically, ...

Instructions for a safe upgrade from ngrx version 2.0 to version 4.0

Is there a direct command to upgrade from ngrx v-2 to ngrx v4 similar to when we upgraded from Angular version 2.0 to version 4.0? I have searched extensively for such a command, but all I could find in the git repository and various blogs is this npm ins ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...

Discover the contents of an Object's key in TypeScript

I currently have a variable of type object. let ref_schema_data: object The value of ref_schema_data: { '$schema': 'http://json-schema.org/draft-07/schema', '$id': 'tc_io_schema_top.json', allOf: [ { type: &a ...

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...

Troubleshooting Issue: Data not appearing on Angular frontend when fetching from Laravel API

Utilizing Laravel for the back end and Angular for the front end development. The code segments related to Angular can be found in employee.component.ts file: import { Component, OnInit } from '@angular/core'; import { DataService } from 'sr ...

Tips for sending the image file path to a React component

Hey, I'm working on a component that has the following structure: import React from "react"; interface CInterface { name: string; word: string; path: string; } export function C({ name, word, path }: CInterface) { return ( < ...

Rearranging items within an array in a React component

Currently, I am facing a situation where I have created a list that dynamically adds a React Node upon clicking a button. The final layout of the model looks like this: Here is the code snippet for your reference: import * as React from 'react' ...

Utilize Angular 9 with an M1 Mac device

Struggling to get my project, which utilizes Node 12 and Angular 9, up and running on my new M1 Mac. I used nvm to install node and the latest npm version, then ran the command npm i -g @angular/cli@9 to install angular. Even though which ng confirms that ...

Why does "excess property checking" seem pleased when I utilize a key from set A or set B, even though "keyof (A|B)" is consistently "never"?

I am diving deeper into Typescript types and encountering some puzzling behavior: interface Person { name: string; } interface Lifespan { birth: number; death?: number; } let k: keyof (Person | Lifespan); //k is never let test1: Person | Life ...

Tips for showcasing the CDK table in Angular without duplicating customer IDs

My CDK table is used to display data, but I am facing an issue with duplicated data in the dataSource as shown below: [ {customerID:"56789", name: "foo", mobile: "123456"}, {customerID:"56789", name: "foo", mobile: "123456"}, {customerID:"12345", name: "f ...

Using browser.actions().mouseMove() in conjunction with sendKeys results in a syntax error

I am currently working on a test automation project and utilizing protractor with the jasmine framework. I am facing an issue while dealing with an autocomplete selection drop-down (for example, a countries' name drop-down). I want to input keys into ...

The application was not functioning properly due to an issue with the getSelectors() function while utilizing @ngrx/entity to

Currently, I am facing an issue with implementing a NgRx store using @ngrx/entity library. Despite Redux Devtools showing my collection loaded by Effect() as entities properly, I am unable to retrieve any data using @ngrx/entity getSelectors. Thus, it seem ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

The subscriber continues to run repeatedly, even after we have removed its subscription

The file brief-component.ts contains the following code where the drawer service is being called: this.assignDrawerService.showDrawer(parameter); In the file drawer-service.ts: private drawerSubject = new BehaviorSubject<boolean>(false); public ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

I'm encountering an issue with my Next.js development server at localhost:3001 where all routes are displaying a 404 not found page. What

Currently working on a Next.js dashboard app and encountering an issue where my localhost keeps redirecting me to the 404 page. This has happened before, but I can't recall how I resolved it. Here is the recurring problem: I attempted deleting the .n ...

Retrieve route parameters in Angular 6 without using promises

I am currently utilizing Angular 6. When working with route parameters, I typically use the following code snippet: this.route.params.subscribe(params => { // params can now be utilized as an object variable }); However, I find myself needing to a ...

I am unable to locate the module '@schematics/angular/utility/config'

I attempted to execute the command below in order to add ngx-bootstrap to my project: ng add ngx-bootstrap Unfortunately, I encountered an error message. The full CLI output is displayed below: i Using package manager: npm √ Found compatible package ver ...