3

I am using mat-table with formArray in it, also I need to Mat-paginator.

But unfortunately pagination not working.

Stackbltiz Demo

Sample Source,

.html

<form [formGroup]="form">
  <table mat-table [dataSource]="dataSource" formArrayName="dates">
    <!-- Row definitions -->
    <tr mat-header-row *matHeaderRowDef="displayColumns"></tr>
    <tr mat-row *matRowDef="let row; let i = index; columns: displayColumns;"></tr>

    <!-- Column definitions -->
    <ng-container matColumnDef="from">
      <th mat-header-cell *matHeaderCellDef> From </th>
      <td mat-cell *matCellDef="let row; let index = index"  [formGroupName]="index"> 
        <input type="date" formControlName="from" placeholder="From date">
      </td>
    </ng-container>

    <ng-container matColumnDef="to">
      <th mat-header-cell *matHeaderCellDef> To </th>
      <td mat-cell *matCellDef="let row; let index = index"  [formGroupName]="index">
        <input type="date" formControlName="to" placeholder="To date">
      </td>
    </ng-container>
  </table>
  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
  <button type="button" (click)="addRow()">Add row</button>
</form>

<pre>{{ form.value | json }}</pre>

.Ts

@ViewChild(MatPaginator) paginator: MatPaginator;
      dataSource = new MatTableDataSource<any>();
      displayColumns = ['from', 'to'];
      form: FormGroup = this.fb.group({ 'dates': this.fb.array([]) });

      constructor(private fb: FormBuilder) { }

      ngOnInit() {
        this.dataSource.paginator = this.paginator;
      }

      get dateFormArray():FormArray {
        return this.form.get('dates') as FormArray;
      }

      addRow() {
        const row = this.fb.group({
          'from'   : null,
          'to'     : null
        });
        this.dateFormArray.push(row);
        this.dataSource.data =  this.dateFormArray.controls;
      }
Aniket Avhad
  • 4,025
  • 2
  • 23
  • 29

1 Answers1

6

Actually there are two issues:

  1. mat-paginator element reference issue in @ViewChild
  2. Getting Actual Index for MatDataSource (because you are having two data structure to list data dataSource and FormArray )

solution for first issue is to import paginator and mat-datasource like this

import { MatPaginator } from "@angular/material/paginator";
import {MatTableDataSource} from '@angular/material/table';

for second issue you have to get actual index like this:

getActualIndex(index : number)    {
    return index + this.paginator.pageSize * this.paginator.pageIndex;
}

and use [formGroupName]="getActualIndex(index)"

WORKING EXAMPLE

Also you can increase page size in drop down as per you add element in formArray.

Akj
  • 7,038
  • 3
  • 28
  • 40