首页 > 解决方案 > 当我输入超过 3 个字符时如何过滤数据

问题描述

嘿,我正在尝试创建一个搜索栏,当我输入超过 3 个字符时,它只显示过滤lastname的表格,(条件为空)

这里是HTML

<mat-form-field>
  <input matInput id="search-field" (keyup)="applyFilter($event.target.value)" placeholder="Search">
</mat-form-field>
<a [routerLink]='["/doctors/new"]' class="doctors-list-newDoctor-button">
  <button mat-raised-button id="doctors-list-newDoctor-button">
    <i class="material-icons">
      add
    </i>
  </button>
</a>
<div>

  <table mat-table matSort [dataSource]="this.displayedDoctors" id="doctors-list-table" (matSortChange)="sortData($event)" class="mat-elevation-z8">
    <ng-container matColumnDef="lastName">
      <th mat-header-cell *matHeaderCellDef mat-sort-header id="doctors- 
        list-lastName-header">lastName</th>
      <td mat-cell *matCellDef="let doctor" class="doctor-lastName">
        {{doctor.lastName}}</td>
    </ng-container>
    <ng-container matColumnDef="firstName">
      <th mat-header-cell *matHeaderCellDef id="doctors-list-firstName- 
        header">firstName</th>
      <td mat-cell *matCellDef="let doctor" class="doctor-firstName">
        {{doctor.firstName}}</td>
    </ng-container>
    <ng-container matColumnDef="format">
      <th mat-header-cell *matHeaderCellDef id="doctors-list-format- 
            header">format</th>
      <td mat-cell *matCellDef="let doctor" class="doctor-inami">
        {{doctor.format}}</td>
    </ng-container>
    <ng-container matColumnDef="inami">
      <th mat-header-cell *matHeaderCellDef id="doctors-list-inami- 
       header">inami</th>
      <td mat-cell *matCellDef="let doctor" class="doctor-format">
        {{doctor.inami}}</td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="DoctorsListHeaders"></tr>
    <tr mat-row *matRowDef="let row; columns: DoctorsListHeaders;" (click)="OpenDoctor(row)"></tr>
  </table>
</div>

这里的模型

export interface Doctor {
  lastName: string;
  firstName: string;
  format: string;
  inami: string;
  _id: string;
}

export const EMPTY_DOCTOR: Doctor = {
  lastName: null,
  firstName: null,
  format: null,
  inami: null,
  _id: null
}

这里是打字稿

applyFilter(filterValue: string) {
  this.filterSearch = filterValue.toLowerCase();

  this.doctorsService.getAll({ lastName: this.filterSearch, inami: this.filterSearch }).subscribe((doctors: Doctor[]) => {
    //this.dataDoctors = doctors;
    this.displayedDoctors.data = this.dataDoctors;
    if (this.filterSearch.length >= 3) {


    }
    if (this.tableSort) {
      this.sortData(this.tableSort);
    }
  });
}  

标签: angularobjectfilter

解决方案


您可以使用过滤管来实现您的目标。

按照ngx-filter-pipe并相应地更改您的代码。使用管道,您可以在输入文本字段时直接过滤数据。您可以根据需要自定义功能。(3个字符后开始搜索)


推荐阅读