3

我正在使用带有 formArray 的 mat-table,还需要 Mat-paginator。

但不幸的是分页不起作用。

Stackbltiz 演示

样品来源,

.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;
      }
4

1 回答 1

4

其实有两个问题:

  1. mat-paginator元素参考问题@ViewChild
  2. 获取实际索引MatDataSource(因为您有两个数据结构来列出数据dataSourceFormArray

第一个问题的解决方案是像这样导入分页器和 mat-datasource

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

对于第二个问题,您必须获得如下实际索引:

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

并使用[formGroupName]="getActualIndex(index)"

工作示例

您还可以根据在 formArray 中添加元素来增加下拉菜单中的页面大小。

于 2020-06-17T07:57:39.233 回答