Я использовал код «Таблица извлечения данных через HTTP» из https://material.angular.io/components/table/examples для отображения данных в mat-таблице. Я хочу добавить пользовательский фильтр выбора к нему. Я обновил код так, чтобы при изменении выпадающего списка снова вызывался ngAfterViewInit и выпадающее значение выбора передавалось в вызов API, но когда элементы на странице меняются и выбирается фильтр, API вызывается несколько раз. Может Кто-нибудь, пожалуйста, помогите в реализации фильтра в этом коде
Пожалуйста, найдите ниже код:
TS файл
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { merge, of as observableOf } from 'rxjs';
import { catchError, map, startWith, switchMap } from 'rxjs/operators';
import { PersonDetail } from '../../shared/model/people';
import { PeopleService } from '../../shared/services/people.service';
/**
* @title People list retrieving data through HTTP
*/
@Component({
selector: 'app-people-list',
templateUrl: './people-list.component.html',
styleUrls: ['./people-list.component.css']
})
export class PeopleListComponent implements AfterViewInit {
filters = [
{value: 'aaa', viewValue: 'aaa'},
{value: 'bbb', viewValue: 'bbb'}
];
displayedColumns: string[] = ['name', 'action'];
data: PersonDetail[] = [];
resultsLength = 0;
isLoadingResults = true;
noRecords = false;
pageSize = 10;
filter: string = "";
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
@ViewChild(MatSort, {static: false}) sort: MatSort;
constructor( private peopleService: PeopleService ) {}
// Update page size when user has changed it
handlePage(e: any) {
this.pageSize = e.pageSize;
}
onfilterSelection( event ) {
this.filter = event.value;
}
ngAfterViewInit() {
// If the user changes the sort order, reset back to the first page.
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
merge(this.sort.sortChange, this.paginator.page)
.pipe(
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.peopleService.getPeople( this.sort.active, this.sort.direction, this.paginator.pageIndex, this.pageSize, this.filter );
}),
map((data : any) => {
// Flip flag to show that loading has finished.
this.isLoadingResults = false;
this.noRecords = false;
this.resultsLength = data.total_count;
return data.items;
}),
catchError(() => {
this.isLoadingResults = false;
// Catch if the API returned empty data.
this.noRecords = true;
return observableOf([]);
})
).subscribe(data => this.data = data);
}
}
HTML файл
<div class="example-container mat-elevation-z8">
<!-- Display Spinner till the results are displayed -->
<div class="example-loading-shade" *ngIf="isLoadingResults || noRecords">
<mat-spinner *ngIf="isLoadingResults"></mat-spinner>
<!-- Display no records message if no data is found -->
<div class="example-rate-limit-reached" *ngIf="noRecords">
No records found.
</div>
</div>
<div class="example-table-container">
<mat-card>
<!-- filter -->
<mat-form-field>
<mat-label>Apply filter</mat-label>
<mat-select (selectionChange)="onfilterSelection($event)">
<mat-option *ngFor="let filter of filters" [value]="filter.value">
{{filter.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</mat-card>
<table mat-table [dataSource]="data" class="example-table" matSort>
<!-- Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
<td mat-cell *matCellDef="let row">{{row.name}}</td>
</ng-container>
<!-- Action Column -->
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef>Action</th>
<td mat-cell *matCellDef="let row">
<mat-icon>edit</mat-icon>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
<!-- Pagination links -->
<mat-paginator [length]="resultsLength" [pageSize]="pageSize" [pageSizeOptions]="[10, 20, 100]" (page)="pageEvent = handlePage($event)" showFirstLastButtons></mat-paginator>
</div>
Мне нужно перезагрузить содержимое таблицы матов в соответствии с выбранным фильтром