@prolina

Проблема с пагинацией в Angular material table?

Здравствуйте! Использую в своем проекте angular material table. Создала shared компонент для таблицы, поскольку таблиц будет несколько. В родительском компоненте через сервис получаю данные с бэкенда, это объект вида: {count: number, items: object []}, где count- общее число записей в бд, а items - сами данные. В моем случае я получаю count: 90, а в items лежит массив из 20 объектов, так сделано на бэкенде, чтобы не получать сразу все значения. Полученные значения я передаю через @Input в дочерний компонент, и получается, что всего таблица состоит из 20 значений ив пагинации - 1 – 20 of 20, хотя должно быть 1 – 20 of 90. Я пробовала напрямую задавать length, но безуспешно(

таблица:
<table mat-table [dataSource]="tableDataSource" matSort (matSortChange)="sortTable($event)">

		<!-- action column -->
		<ng-container *ngIf="rowActionIcon?.length" [matColumnDef]="rowActionIcon">
			<mat-header-cell *matHeaderCellDef></mat-header-cell>
			<mat-cell *matCellDef="let element" [id]="rowActionIcon" (click)="emitRowAction(element)">
				<button mat-button>
					<mat-icon>remove_shopping_cart</mat-icon>
				</button>
			</mat-cell>
		</ng-container>


		<ng-container *ngFor="let tableColumn of tableColumns" [cdkColumnDef]="tableColumn.dataKey">

			<!-- if sortable column header -->
			<ng-container *ngIf="tableColumn.isSortable; else notSortable">
				<mat-header-cell *cdkHeaderCellDef [mat-sort-header]="tableColumn.name"
						[arrowPosition]="tableColumn.position === 'right' ? 'before' : 'after'">
					{{tableColumn.name}}
				</mat-header-cell>

			</ng-container>
			<!-- else not sortable -->
			<ng-template #notSortable>
				<mat-header-cell *matHeaderCellDef [class.text-right]="tableColumn.position == 'right'">
					{{tableColumn.name}}
				</mat-header-cell>
			</ng-template>

			<!-- column data -->
			<mat-cell *cdkCellDef="let element" [class.text-right]="tableColumn.position == 'right'">
				{{tableColumn.cell(element)}}
				<!--					{{element | dataPropertyGetter: tableColumn.dataKey}}-->
			</mat-cell>

		</ng-container>
					<mat-header-row *matHeaderRowDef="displayedColumns;"></mat-header-row>
					<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
	</table>

	<!-- Pagination -->
	<mat-paginator 
		*ngIf="isPageable"
		[pageIndex]="0"
		[pageSizeOptions]="paginationSizes"
		[pageSize]="defaultPageSize"
		showFirstLastButtons
		[length]="tableLength"
	>
	</mat-paginator>


public tableDataSource = new MatTableDataSource([]);
	public displayedColumns: string[];
	@Input() length: number;
	@ViewChild(MatPaginator, {static: false}) matPaginator: MatPaginator;
	@ViewChild(MatSort, {static: false}) matSort: MatSort;

	@Input() isPageable = false;
	@Input() isSortable = false;
	@Input() isFilterable = false;
	@Input() tableColumns: TableColumn[];
	@Input() rowActionIcon: string;
	@Input() paginationSizes: number[];
	@Input() defaultPageSize;
	@Input() tableLength: number;

	@Output() sort: EventEmitter<Sort> = new EventEmitter();
	@Output() rowAction: EventEmitter<any> = new EventEmitter<any>();

	// this property needs to have a setter, to dynamically get changes from parent component
	@Input() set tableData(data: KeywordCollectionModel) {
		this.setTableDataSource(data);
	}

	constructor() {}

	ngOnChanges(changes: SimpleChanges): void {
		if(changes.tableColumns.currentValue) {
			const columnNames = this.tableColumns.map((tableColumn: TableColumn) => tableColumn.dataKey);
			// this.columnsToDisplay = this.displayedColumns.map(c => c.columnDef);
			if (this.rowActionIcon) {
				this.displayedColumns = [this.rowActionIcon, ...columnNames];
			} else {
				this.displayedColumns = columnNames;
			}
		}
	}

	// we need this, in order to make pagination work with *ngIf
	ngAfterViewInit(): void {
		this.tableDataSource.paginator = this.matPaginator;
	}

	setTableDataSource(data: any) {
		this.tableDataSource = new MatTableDataSource<any>(data);
		this.tableDataSource.paginator = this.matPaginator;
		this.tableDataSource.sort = this.matSort;
	}

	applyFilter(event: Event) {
		const filterValue = (event.target as HTMLInputElement).value;
		this.tableDataSource.filter = filterValue.trim().toLowerCase();
	}

	sortTable(sortParameters: Sort) {
		// defining name of data property, to sort by, instead of column name
		sortParameters.active = this.tableColumns.find(column => column.name === sortParameters.active).dataKey;
		this.sort.emit(sortParameters);
	}

	emitRowAction(row: any) {
		this.rowAction.emit(row);
	}
}


родительский компонент:

<fo-table
	[tableData]="data"
	[tableColumns]="displayedColumns"
	[isFilterable]="true"
	[isPageable]="true"
	[paginationSizes]="[20,50,100]"
	[defaultPageSize]="20"
	[tableLength]="tableLength"
	[rowActionIcon]="'remove_shopping_cart'"
	></fo-table>
  • Вопрос задан
  • 160 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы