Miért fontos a szűrő egy táblázatnál?

Amikor sok adatot jelenítesz meg, hamar fogják igényelni a felhasználók a szűrési lehetőséget. Még jobb, ha azt is ki tudják választani, hogy melyik oszlop alapján szeretnének szűrni. A videóban mind a kettőt megmutatom neked.

Nézd meg a videót


Github Repo

https://github.com/cherryApp/ast-mat-table

Szöveges segítség

Három lépésben oldottam meg a problémát:

  • Felvettem a szükséges osztályokat az app.module.ts fájlba:
import { FormsModule } from '@angular/forms';
//
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
//
MatFormFieldModule,
MatInputModule,
MatSelectModule,
FormsModule,
  • Ezután megírtam a szükséges metódusokat a filter.component.ts -ben:
currentFilterKey: string;
// 
applyFilter(event: Event): void {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
}
// 
this.dataSource.filterPredicate = (data: User, filter: string) => {
    const key = this.currentFilterKey || '';
    const source = key ? String(data[key]) : JSON.stringify(data);
    return source.toLowerCase().includes(filter.toLowerCase());
};
  • Végül módosítottam a sablont filter.component.html:
<mat-form-field style="margin-right: 1rem;">
    <mat-label>Field</mat-label>
    <mat-select [(ngModel)]="currentFilterKey">
        <mat-option [value]="''">all field</mat-option>
        <mat-option *ngFor="let col of displayedColumns" [value]="col">
        {{ col }}
        </mat-option>
    </mat-select>
</mat-form-field> 
<mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (keyup)="applyFilter($event)" 
        placeholder="type a phrase">
</mat-form-field>

That's it!